Caution. Don't use for…in to iterate over an array, use it to iterate over the properties of an object.
That said, this question still applies to for…of loops.
警告。不要使用for ...来遍历数组,使用它来迭代对象的属性。也就是说,这个问题仍适用于...循环。
I understand that the basic for…in syntax in JavaScript looks like this:
我理解JavaScript中语法的基本原理如下所示:
for (var obj in myArray) {
// ...
}
But how do I get the loop counter/index? I know I could probably do something like:
但是如何获得循环计数器/索引?我知道我可能做的事情如下:
var i = 0
for (var obj in myArray) {
alert(i)
i++
}
Or even the good, old:
甚至是好的,旧的:
var i
for (i = 0; 1 < myArray.length; i++) {
var obj = myArray[i]
alert(i)
}
But I would rather use the simpler for-in loop. I think they look better and make more sense.
但我宁愿使用更简单的for-in循环。我认为它们看起来更好,更有意义。
But is there a simpler or more elegant way?
但是有更简单或更优雅的方式吗?
In Python it's easy:
在Python中很简单:
for i, obj in enumerate(myArray):
print i
6 个解决方案
#1
225
for…in
iterates over property names, not values, and does so in an unspecified order (yes, even after 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:
for ... in迭代属性名称,而不是值,并以未指定的顺序执行(是的,即使在ES6之后)。您不应该使用它来迭代数组。对于他们来说,有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循环而不是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);
}
演示
If you actually did mean for…in
– enumerating properties – you would need an additional counter. Object.keys(obj).forEach
could work, but it only includes own properties; for…in
includes enumerable properties anywhere on the prototype chain.
如果你确实意味着... in - 枚举属性 - 你需要一个额外的计数器。 Object.keys(obj).forEach可以工作,但它只包含自己的属性; for ... in包括原型链上任何位置的可枚举属性。
#2
75
In ES6, it is good to use for - of loop. You can get index in for of like this
在ES6中,最好使用for-of循环。您可以获得这样的索引
for (let [index, val] of array.entries()) {
// your code goes here
}
Note that Array.entries()
returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.
注意,Array.entries()返回一个迭代器,它允许它在for-of循环中工作;不要将它与Object.entries()混淆,后者返回一个键值对数组。
#3
15
Solution for small array collections:
小数组集合的解决方案:
for (var obj in arr) {
var i = Object.keys(arr).indexOf(obj);
}
arr - ARRAY, obj - KEY of current element, i - COUNTER/INDEX
arr - ARRAY,obj - 当前元素的关键字,i - COUNTER / INDEX
Notice: Method keys() is not available for IE version <9, you should use Polyfill code. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
注意:方法键()不适用于IE版本<9,您应该使用Polyfill代码。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
#4
11
For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.
For-in-loops迭代Object的属性。不要将它们用于数组,即使它们有时也可以工作。
Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).
然后,对象属性没有索引,它们都是相等的,不需要按确定的顺序运行。如果要计算属性,则必须设置额外的计数器(如第一个示例中所示)。
loop over an Array:
循环数组:
var a = [];
for (var i=0; i<a.length; i++) {
i // is the index
a[i] // is the item
}
loop over an Object:
循环对象:
var o = {};
for (var prop in o) {
prop // is the property name
o[prop] // is the property value - the item
}
#5
5
As others have said, you shouldn't be using for..in to iterate over an array.
正如其他人所说,你不应该使用for..in迭代数组。
for ( var i = 0, len = myArray.length; i < len; i++ ) { ... }
If you want cleaner syntax, you could use forEach:
如果您想要更清晰的语法,可以使用forEach:
myArray.forEach( function ( val, i ) { ... } );
If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.
如果要使用此方法,请确保包含ES5填充程序以添加对旧版浏览器的支持。
#6
4
How about this
这个怎么样
let numbers = [1,2,3,4,5]
numbers.forEach((number, index) => console.log(`${index}:${number}`))
#1
225
for…in
iterates over property names, not values, and does so in an unspecified order (yes, even after 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:
for ... in迭代属性名称,而不是值,并以未指定的顺序执行(是的,即使在ES6之后)。您不应该使用它来迭代数组。对于他们来说,有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循环而不是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);
}
演示
If you actually did mean for…in
– enumerating properties – you would need an additional counter. Object.keys(obj).forEach
could work, but it only includes own properties; for…in
includes enumerable properties anywhere on the prototype chain.
如果你确实意味着... in - 枚举属性 - 你需要一个额外的计数器。 Object.keys(obj).forEach可以工作,但它只包含自己的属性; for ... in包括原型链上任何位置的可枚举属性。
#2
75
In ES6, it is good to use for - of loop. You can get index in for of like this
在ES6中,最好使用for-of循环。您可以获得这样的索引
for (let [index, val] of array.entries()) {
// your code goes here
}
Note that Array.entries()
returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.
注意,Array.entries()返回一个迭代器,它允许它在for-of循环中工作;不要将它与Object.entries()混淆,后者返回一个键值对数组。
#3
15
Solution for small array collections:
小数组集合的解决方案:
for (var obj in arr) {
var i = Object.keys(arr).indexOf(obj);
}
arr - ARRAY, obj - KEY of current element, i - COUNTER/INDEX
arr - ARRAY,obj - 当前元素的关键字,i - COUNTER / INDEX
Notice: Method keys() is not available for IE version <9, you should use Polyfill code. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
注意:方法键()不适用于IE版本<9,您应该使用Polyfill代码。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
#4
11
For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.
For-in-loops迭代Object的属性。不要将它们用于数组,即使它们有时也可以工作。
Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).
然后,对象属性没有索引,它们都是相等的,不需要按确定的顺序运行。如果要计算属性,则必须设置额外的计数器(如第一个示例中所示)。
loop over an Array:
循环数组:
var a = [];
for (var i=0; i<a.length; i++) {
i // is the index
a[i] // is the item
}
loop over an Object:
循环对象:
var o = {};
for (var prop in o) {
prop // is the property name
o[prop] // is the property value - the item
}
#5
5
As others have said, you shouldn't be using for..in to iterate over an array.
正如其他人所说,你不应该使用for..in迭代数组。
for ( var i = 0, len = myArray.length; i < len; i++ ) { ... }
If you want cleaner syntax, you could use forEach:
如果您想要更清晰的语法,可以使用forEach:
myArray.forEach( function ( val, i ) { ... } );
If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.
如果要使用此方法,请确保包含ES5填充程序以添加对旧版浏览器的支持。
#6
4
How about this
这个怎么样
let numbers = [1,2,3,4,5]
numbers.forEach((number, index) => console.log(`${index}:${number}`))