在 JavaScript 中使用 for...of 语法获取循环计数器/索引 [英] Get loop counter/index using for…of syntax in JavaScript

查看:21
本文介绍了在 JavaScript 中使用 for...of 语法获取循环计数器/索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题仍然适用于 for...of 循环.> 不要使用 for...in 来迭代 Array,用它来迭代对象的属性.也就是说,这个

Caution:

question still applies to for…of loops.> Don't use for…in to iterate over an Array, use it to iterate over the properties of an object. That said, this

<小时>

我了解 JavaScript 中基本的 for...in 语法如下所示:

for (var obj in myArray) {
    // ...
}

但是我如何获得循环计数器/索引?

var i = 0;
for (var obj in myArray) {
    alert(i)
    i++
}

甚至是旧的:

for (var i = 0; i < myArray.length; i++) {
    var obj = myArray[i]
    alert(i)
}

但我宁愿使用更简单的 for-in 循环.我认为它们看起来更好,更有意义.

But I would rather use the simpler for-in loop. I think they look better and make more sense.

有没有更简单或更优雅的方法?

Is there a simpler or more elegant way?

for i, obj in enumerate(myArray):
    print i

推荐答案

for...in 迭代属性名称,而不是值,并且这样做 以未指定的顺序(是的,即使在 ES6 之后).你不应该用它来迭代数组.对于他们来说,ES5 的 forEach 方法将值和索引都传递给你给它的函数:

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:

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

或者 ES6 的 Array.prototype.entries,现在支持跨当前浏览器版本:

Or ES6’s Array.prototype.entries, which now has support across current browser versions:

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}

对于一般的可迭代对象(您将使用 for...of 循环而不是 for...in),但是没有任何内置内容:

For iterables in general (where you would use a for…of loop rather than a for…in), there’s nothing built-in, however:

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

演示

如果您确实是指 for...in – 枚举属性 – 您将需要一个额外的计数器.Object.keys(obj).forEach 可以工作,但它只包含自己的 属性;for...in 在原型链的任何地方都包含可枚举的属性.

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.

这篇关于在 JavaScript 中使用 for...of 语法获取循环计数器/索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆