【发布时间】:2016-03-24 18:26:27
【问题描述】:
我们可以使用 for-of 循环访问数组元素:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
如何修改此代码以也访问当前索引?我想使用 for-of 语法来实现这一点,既不是 forEach 也不是 for-in。
【问题讨论】:
标签: javascript ecmascript-6 for-of-loop
我们可以使用 for-of 循环访问数组元素:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
如何修改此代码以也访问当前索引?我想使用 for-of 语法来实现这一点,既不是 forEach 也不是 for-in。
【问题讨论】:
标签: javascript ecmascript-6 for-of-loop
只需在循环之前创建一个变量并分配一个整数值。
let index = 0;
然后在循环范围内使用addition assignment operator
index += 1;
就是这样,查看下面的 sn-p 示例。
let index = 0;
for (const j of [1, 2, 3, 4, 5]) {
index += 1;
console.log('index ',index);
}
【讨论】:
你也可以使用 JavaScript 来解决你的问题
iterate(item, index) {
console.log(`${item} has index ${index}`);
//Do what you want...
}
readJsonList() {
jsonList.forEach(this.iterate);
//it could be any array list.
}
【讨论】:
如果需要index也可以自己处理索引,如果需要key就不行了。
let i = 0;
for (const item of iterableItems) {
// do something with index
console.log(i);
i++;
}
【讨论】:
另一种方法是使用Array.prototype.forEach() as
Array.from({
length: 5
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {
console.log(val, index)
})
【讨论】:
es6for...in
for(const index in [15, 64, 78]) {
console.log(index);
}
【讨论】:
for...of 循环而不是 for...in
for...in 是原始 ECMAScript 规范(即“es1”)的一部分。另外,请注意for...in 用于迭代对象属性。虽然它可以迭代数组,但它可能不会按照预期的顺序进行。在MDN documentation中查看更多信息
在这个充满华丽的新本机功能的世界中,我们有时会忘记基础知识。
for (let i = 0; i < arr.length; i++) {
console.log('index:', i, 'element:', arr[i]);
}
干净、高效,您仍然可以break 循环。奖金!你也可以用i--从头开始倒退!
附加说明:如果您在循环中大量使用该值,您可能希望在循环顶部执行const value = arr[i]; 以获得简单易读的参考。
【讨论】:
break 和 for-of 和 for (let [index, value] of array.entries()) 更容易阅读。后退就像添加.reverse() 一样简单。
for 循环比for of array.entries() 快约8 倍。 jsbench.me/6dkh13vqrr/1
在for..of 循环中,我们可以通过array.entries() 实现此目的。 array.entries 返回一个新的 Array 迭代器对象。迭代器对象知道如何从一个可迭代对象中访问项目,同时跟踪其在该序列中的当前位置。
当在迭代器上调用next() 方法时,会生成键值对。在这些键值对中,数组 index 是键,数组项是值。
let arr = ['a', 'b', 'c'];
let iterator = arr.entries();
console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']
for..of 循环基本上是一个构造,它消耗一个可迭代对象并循环遍历所有元素(使用引擎盖下的迭代器)。我们可以通过以下方式将其与array.entries() 结合起来:
array = ['a', 'b', 'c'];
for (let indexValue of array.entries()) {
console.log(indexValue);
}
// we can use array destructuring to conveniently
// store the index and value in variables
for (let [index, value] of array.entries()) {
console.log(index, value);
}
【讨论】:
对于那些使用不是Array 甚至不是类似数组的对象的人,您可以轻松地构建自己的可迭代对象,这样您仍然可以将for of 用于像localStorage 这样实际上只有length 的东西:
function indexerator(length) {
var output = new Object();
var index = 0;
output[Symbol.iterator] = function() {
return {next:function() {
return (index < length) ? {value:index++} : {done:true};
}};
};
return output;
}
然后给它一个数字:
for (let index of indexerator(localStorage.length))
console.log(localStorage.key(index))
【讨论】:
在 html/js 上下文中,在现代浏览器上,除了数组之外,我们还可以使用其他可迭代对象 [Iterable].entries():
for(let [index, element] of document.querySelectorAll('div').entries()) {
element.innerHTML = '#' + index
}
【讨论】:
entries 方法。
for (const index of [1, 2, 3, 4, 5].keys()) {
console.log(index);
}
如果要同时访问键和值,可以使用Array.prototype.entries() 和destructuring:
for (const [index, value] of [1, 2, 3, 4, 5].entries()) {
console.log(index, value);
}
【讨论】:
.entries() 测试了for-of,它的速度是.forEach() 的两倍。 jsperf.com/for-of-vs-foreach-with-index
yield 关键字创建范围问题。但是我需要访问我的用例的索引,所以......我猜是基本的旧 ;; 循环。
.entires() 的 for-of 循环有什么问题?
Array#entries 返回索引和值,如果您需要两者:
for (let [index, value] of array.entries()) {
}
【讨论】:
document.styleSheets[0].cssRules.entries() 甚至 document.styleSheets.entries() 可能还有许多其他 DOM 可迭代结构。还是得用_.forEach() from lodash
for (var value of document.styleSheets) {}。如果确实需要索引,可以先通过Array.from 将值转换为数组:for (let [index, value] of Array.from(document.styleSheets)) {}。
Array.from 是 FTW