The best way in my opinion is to use the Array.forEach function. If you cannot use that I would suggest to get the polyfill from MDN to. To make iit available, it is certainly the safest way to iterate over an array in JavaScript.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEachArray.prototype.forEach()
So as others has suggested, this is almost always what you want:
var numbers = [1,11,22,33,44,55,66,77,88,99,111];
var sum = 0;
numbers.forEach(function(n){
sum += n;
});
This ensures that anything you need in the scope of processing the array stays within that scope, and that you are only processing the values of the array, not the object properties and other members, which is what for ..for ..
in does.
usingUsing a regular c style forC-style for
loop works in most cases, it. It is just important to remember that everything within the loop shares it'sits scope with the rest of your program, the { } does not create a new scope.
Hence:
var sum = 0;
var numbers = [1,11,22,33,44,55,66,77,88,99,111];
for(var i = 0; i<numbers.length; ++i){
sum += numbers[i];
}
alert(i);
will output "11" - which may or may not be what you want.
WorkingA working jsFiddle example: https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/