是否有 JavaScript 等同于 Python 的 for 循环?

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

所以我很失望地发现 JavaScript 的 for ( var in array/object) 不等同于 pythons for var in list:

在 JavaScript 中,您正在遍历索引本身,例如

0, 
1,
2,
... 

与 Python 一样,您正在迭代索引指向的值,例如

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

是否有一个标准的 JavaScript 相当于 Python 的循环机制?

免责声明:

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.

对于数组最相似的是forEach循环(当然索引是可选的)

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

所以你会得到以下输出:

1
0
2
1
3
2
4
3

在下一版本的 ECMAScript(ECMAScript6 又名 Harmony)中将是 for-of construct:

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

for-of 可用于迭代各种对象、数组、映射、集合和自定义可迭代对象。从这个意义上说,它非常接近 Python 的 for-in

我不确定我是否看到了很大的不同。在给定的 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]);

如前所述,您可以将 forEach 用于数组或对象...这是一个对象:

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));
});