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

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

问题描述


警告:



问题仍然适用于循环。>不要在中使用来迭代数组,使用它来迭代
而不是属性一个物体。也就是说,这个

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中的语法如下所示:


I understand that the basic for…in syntax in JavaScript looks like this:

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

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

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



甚至是旧的:



Or even the good old:

for (var i = 0; 1 < 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);
}

对于一般的iterables(你将使用对于循环而不是中的,没有内置的东西,但是:

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中的语法获取循环计数器/索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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