JavaScript For Loop


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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]);

URL: http://www.sitepoint.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.