Forums > Javascript

for x in y loop behaviour

July 8, 2013 | 9:09 am

Hi all,

Why, unlike Python for example, the following post(item) code outputs the index of each item in the list, not their value.

function test() {
var list = ['a','b','c','d'];
for (item in list) {
post(item);
}
}


July 8, 2013 | 1:22 pm

In javascript, you’d want:

function test() {
var list = ['f','b','c','d'];
for (item in list) {
post(list[item]);
}
}

Although that’s not a great practice. See:

http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/


July 8, 2013 | 1:50 pm

Hey mike,

Thanks for the link!
I know how to get the right output, I’m just curious why the implementation is different from python.

ps. looking forward to ICMC ;)



Lee
July 16, 2013 | 2:16 am

for (var item in list) would be preferable also…


July 17, 2013 | 1:57 am

good point, lee,
for (var item in list) to make sure that the variable item is not shared with other javascripts


Viewing 5 posts - 1 through 5 (of 5 total)