Posted By

danielwrobert on 01/10/11


Tagged

javascript basics


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

chrisaiv


JavaScript For Loop


 / Published in: JavaScript
 

URL: http://www.sitepoint.com

I saw this useful little variation of a for loop in a tutorial by Kevin Yank at Sitepoint. By adding an additional variable "ii" in the loop's arguments, you can avoid having your program calculate the length of your array every time it loops through. Saves on processing. Delightful.

  1. var numbers = [1, 2, 3, 4, 5];
  2.  
  3. for (var i = 0, var ii = numbers.length; i < ii; i++)
  4. {
  5. numbers[i] *= 2;
  6. }
  7.  
  8. alert("The last item in the array is " + numbers[numbers.length - 1]);

Report this snippet  

You need to login to post a comment.