我们可以使用for-of循环访问数组元素:

For (const j of [1,2,3,4,5]) { console.log (j); }

我如何修改这段代码来访问当前索引?我想使用for-of语法来实现这一点,既不是forEach也不是for-in。


当前回答

您还可以使用JavaScript来解决您的问题

迭代(item, index) { Console.log (' ${item}有索引${index} '); //做你想做的… } readJsonList () { jsonList.forEach (this.iterate); //它可以是任何数组列表。 }

其他回答

在html/js上下文中,在现代浏览器中,对于数组以外的其他可迭代对象,我们也可以使用[iterable].entries():

for(let [index, element] of document.querySelectorAll('div').entries()) {

    element.innerHTML = '#' + index

}

对于那些使用的对象不是数组,甚至不是类似数组的对象,你可以很容易地构建自己的iterable,这样你仍然可以使用For或For像localStorage这样只有长度的东西:

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

你可以尝试使用里面的indexOf方法。循环

let arrData = [15, 64, 78] for (arrData的const数据){ console.log(“数据值”,数据,“数据索引”,arrData.indexOf(数据)); }

您还可以使用JavaScript来解决您的问题

迭代(item, index) { Console.log (' ${item}有索引${index} '); //做你想做的… } readJsonList () { jsonList.forEach (this.iterate); //它可以是任何数组列表。 }

es6的……

for(const index in [15, 64, 78]) {                        
    console.log(index);
}