【问题标题】:How can the current number of i be accessed in a for of loop?如何在 for of 循环中访问当前的 i 数量?
【发布时间】:2016-02-05 22:57:02
【问题描述】:

给定一个 for of 循环,分配的变量的值(在此示例中为i)等于array[i] 如果它是一个正常的 for 循环则等于。如何访问i当前所在的数组的索引。

我想要什么

let array = ["one", "two", "three"];

for (let i of array) {
  console.log(i);// normally logs cycle one : "one", cycle two : "two", cycle three : "three".
  console.log(/*what equals the current index*/);// what I want to log cycle one : 1, cycle two : 2, cycle three : 3. 
}

【问题讨论】:

  • 我对 javascript 了解不多,但在其他语言中,您会循环遍历数组的长度,然后遍历数组本身。
  • let array = ["one", "two", "three"]; let index=0; for (let i of array) { console.log(i); console.log(index++) }

标签: javascript ecmascript-6


【解决方案1】:

没有什么简单的...如果您想在数组的循环中“简单地访问”项目和索引,请使用forEach,例如

array.forEach(function(item, index) { 
... 
});

或作为 T.J. Crowder 指针出来了(我错过了 ES6 标签)

array.forEach((item, index) => { 
    ... 
});

像许多编程语言一样,javascript 有多种方法可以做类似的事情,技能在于为工作选择正确的工具

【讨论】:

  • 这似乎是描述问题的最佳解决方案。
  • 在 ES6 中,实际上没有理由再使用 forEach
  • 我很好奇 - 你会用什么代替......嗯......刚刚看到for/of.entries回答......
【解决方案2】:

你是说这个吗?

array = ["one", "two", "three"];

for (i = 0; i < array.length; i++) {
  console.log(i); // Logs the current index number;
  console.log(array[i]); // Logs the index matching in the array;
}

Kaiido 中的一个很好的comment 是您可以使用它直接从数组中获取值作为变量。

for (var ind = 0, i=array[ind]; ind < array.length; i=array[++ind]) {
    console.log(i);
    console.log(ind);
}

【讨论】:

  • 是的,但我希望只需 i 即可轻松访问数组中的同上,而不必使用 array[i]
  • @user5448026,你的问题很难理解:p,但为什么不使用array[i]?有问题吗?
  • array[i] 有什么不容易简单的?
  • @Kaiido:实际上这不起作用,因为您不会在每次迭代中更新i
  • @Bergi oups,你是对的。它应该是for (var ind = 0,i=array[ind] ; ind &lt; array.length; i=array[++ind]) { console.log(i); console.log(ind); },但我个人总是更喜欢arr[x] 表示法
【解决方案3】:

使用indexOf 获取索引

let array = ["one", "two", "three"];

for (let i of array) {
  console.log(i);
  console.log(array.indexOf(i));
}

注意: 仅适用于没有重复的数组。

【讨论】:

  • let array = ["one", "two", "three", "one"];怎么样
  • true,虽然问题没有提到重复。更新了我的答案。
  • 对但是这会返回数组中值的第一个索引,这与“正在访问的数组的实际索引”不同
【解决方案4】:

您可以使用entries 函数。它将为数组中的每个条目返回一个索引/值对,例如:

[0, "one"]
[1, "two"]
[2, "three"]

将此与array destructuring 结合使用,将每个条目解析为适当的变量名称:

const arr = ["one", "two", "three"]
for(const [index, value] of arr.entries()) {
  console.log(index, value);
}

Babel REPL Example

【讨论】:

  • 我喜欢你的回答,而且它在技术上是正确的,但对我来说使用 index 而不是 key 似乎更直观。
  • @AndrewWillems 有趣的是,我实际上(错误地)假设entries() 也会迭代数组上设置的任何属性(即arr.one = "1")但实际上并非如此,所以你'是的,应该是[index, value]
  • 郑重声明,key 在技术上是正确的,即使它是用于访问这些值的正确/唯一关键字。例如for (let i of arr.keys()) {console.log(i);} 产生“0, 1, 2”。但是,为了再次说明这一点略有不同,虽然 JavaScript 数组 确实 有一种键形式(请注意您指出),但它们是顺序数字键,我们通常将它们视为 index es(或索引,或任何你想要的拼写)。因此,关于代码可读性,我认为您重新编辑答案以使用 index 而不是 key 仍然是最好的。
  • 这应该是问题恕我直言的正确答案。
  • 为了 Typescript 的有效性,在 arr.entries() 周围添加 Array.from(): Array.from(arr.entries()) 以防止 TS2488。
【解决方案5】:

您可以使用entries() 函数获取包含索引的迭代器。

for (let [index, value] of [1, 2, 3].entries())
  console.log(index + ':' + value);

或者,如果您不喜欢 let [,] 表示法:

for (let entry of [1, 2, 3].entries())
  console.log(entry[0]+ ':' + entry[1]);

但是其他类似数组的呢?好吧,你可以很容易地自己照顾它,真的

let index = 0;
for (let ch of 'abcd') {
  ++index;
  //your code
}

或者,你可以很容易地patch in你自己的实现

Object.defineProperty(String.prototype, 'indexerator', {get:function() {
    var elements = this[Symbol.iterator]();
    var index = 0;
    var output;

    return {
        [Symbol.iterator] : function() { return this; },
        next : function() {
            if (!(output = elements.next()).done)
                output.value = [index++, output.value];
            return output;
        }
    };
}});

/*other code*/

for (let [index, ch] of 'abcd'.indexerator)
  console.log(index + ':' + ch);

demonstrations

【讨论】:

  • 对于字符串,您可以只包含.split('') 将字符串转换为字符数组,然后照常进行,即for (let [index, ch] of 'abcd'.split('').entries()) {...}
  • 酷。这只是一个易于理解的示例,您的解决方案适用于字符串,但如果您需要修补,例如 NodeList 在稍旧的 webkit 浏览器上(出于某种原因,支持迭代器但尚未制作 NodeList),则不会帮助您成为一个自己)。每次你想在一个项目中做这样的事情时都必须写那个长表达式会很笨拙,在这种情况下你可能最终会把它变成一个函数,无论如何使它不比这里的解决方案复杂(@ 987654333@,修补功能只是在某个实用程序中隐藏后才定义的)。
  • @AndrewWillems 如果字符串没有转换为数组会浪费内存并导致问题?最好添加自己的索引。
【解决方案6】:

或者

array = ["one", "two", "three"];

for (i = 0, item; item=array[i]; i++) {
  console.log(i); // Logs the current index number;
  console.log(item); // Logs the current item in the array;
}

【讨论】:

    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 2016-03-24
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多