for…in
iterates over property names, not values, and does so in an unspecified order (yes, even after ES6).
(for…in
迭代属性名称,而不是值,并以未指定的顺序执行 (是的,即使在ES6之后)。)
You shouldn't use it to iterate over arrays.(您不应该使用它来迭代数组。)
For them, there's ES5's forEach
method that passes both the value and the index to the function you give it:(对于他们来说,有ES5的forEach
方法,它将值和索引传递给你给它的函数:)
var myArray = [123, 15, 187, 32];
myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});
// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32
Or ES6's Array.prototype.entries
, which now has support across current browser versions:
(或ES6的Array.prototype.entries
,现在支持当前的浏览器版本:)
for (const [i, value] of myArray.entries()) {
console.log('%d: %s', i, value);
}
For iterables in general (where you would use a for…of
loop rather than a for…in
), there's nothing built-in, however:
(对于一般的iterables(你将使用for…of
循环而不是for…in
),没有内置的东西,但是:)
function* enumerate(iterable) {
let i = 0;
for (const x of iterable) {
yield [i, x];
i++;
}
}
for (const [i, obj] of enumerate(myArray)) {
console.log(i, obj);
}
demo
(演示)
If you actually did mean for…in
– enumerating properties – you would need an additional counter.
(如果你真的意味着for…in
- 枚举属性 - 你需要一个额外的计数器。)
Object.keys(obj).forEach
could work, but it only includes own properties;(Object.keys(obj).forEach
可以工作,但它只包含自己的属性;)
for…in
includes enumerable properties anywhere on the prototype chain.(for…in
包括原型链上任何位置的可枚举属性。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…