Reputation: 4618
This for each...in loop is not running, allthough it's a direct copy from the mozilla Javascript guide about the for each...in statement.
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for each (var item in obj) {
sum += item;
}
alert(sum); // prints "26", which is 5+13+8
jsFiddle: http://jsfiddle.net/4fVSB/1/
I'm getting this error:
SyntaxError: missing ( after for for each (var item in obj) {
Could this have something to do with my javascript version. For some reason my FF has javascript version 1.5 while i do have FF 24.0 installed. Shouldn't this version of FF have the latest javascript version?
Fiddle to see what version of js i have: http://jsfiddle.net/Ac6CT/
Thx,
Upvotes: 1
Views: 1864
Reputation: 3170
The for each...in statement is deprecated as the part of ECMA-357 (E4X) standard. E4X will be disabled by default and removed in the future, but for each...in will not be disabled and removed because of backward compatibility considerations. Consider using for...of instead.
Upvotes: 0
Reputation: 33173
From this page it appears that "for each" (for-space-each) is deprecated. So the engine is looking for a ( after for, e.g. for(
I would recommend using the underscore library _.each or the equivalent in jquery, e.g. $(..).each()
Upvotes: 0
Reputation: 2279
Just use regular for loop to avoid any consequences
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for (var item in obj) {
sum += obj[item];
}
alert(sum); // prints "26", which is 5+13+8
The for each...in statement is deprecated as the part of ECMA-357 (E4X) standard. E4X will be disabled by default and removed in the future, but for each...in will not be disabled and removed because of backward compatibility considerations. Consider using for...of instead. (Please refer to bug 791343.)
Upvotes: 2
Reputation: 2988
The right syntax is just for(var item in obj)
, without the each.
And then in the actual loop you have to acces the numeric value (i.e. 5, 13 etc.) with obj[item]
.
Your code should look like this at the end:
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for(var item in obj) {
if(obj.hasOwnProperty(item)){
sum += obj[item];
}
}
alert(sum);
The hasOwnProperty
function makes sure you don't accidentaly loop over inherited methods.
Upvotes: 4