简体   繁体   中英

Is there a JavaScript equivalent to Python's for loops?

So I was dissapointed to find out that JavaScript's for ( var in array/object) was not equivalent to pythons for var in list: .

In JavaScript you are iterating over the indices themselves eg

0, 
1,
2,
... 

where as with Python, you are iterating over the values pointed to by the indices eg

"string var at index 0", 
46, 
"string var at index 2",
["array","of","values"],
...

Is there a standard JavaScript equivalent to Python's looping mechanism?

Disclaimer:

I am aware that the for (var in object) construct is meant to be used to iterate over keys in a dictionary and not generally over indices of an array. I am asking a specific question that pertains to use cases in which I do not care about order(or very much about speed) and just don't feel like using a while loop.

for an array the most similar is the forEach loop (of course index is optional)

[1,2,3,4,].forEach(function(value,index){
  console.log(value);
  console.log(index);
});

So you will get the following output:

1
0
2
1
3
2
4
3

In the next version of ECMAScript (ECMAScript6 aka Harmony) will be for-of construct :

for (let word of ["one", "two", "three"]) {
  alert(word);
}

for-of could be used to iterate over various objects, Arrays, Maps, Sets and custom iterable objects. In that sense it's very close to Python's for-in .

I'm not sure I see MUCH difference. It's easy to access the value at a given index/key

var list = [1,2,3,4,5];

// or...

var list = {a: 'foo', b: 'bar', c: 'baz'};
for (var item in list) console.log(list[item]);

and as mentioned, you could use forEach for arrays or objects... heres an obj:

var list = {a: 'foo', b: 'bar', c: 'baz'}; 

Object.keys(list).forEach(function(key, i) {
    console.log('VALUE: \n' + JSON.stringify(list[key], null, 4));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM