我知道在for-of
循环中,可以使用Array.entries()
方法。正如概述的那样,这在正常情况下工作得很好——https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries.
然而,如果我尝试做一些类似的事情:
for (const [i, foo] of document.getElementsByClassName('foo').entries())
{
console.log(`i = ${i}, foo = ${foo}`);
}
我被告知:
Uncaught TypeError: document.getElementsByClassName.entries is not a function or its return value is not iterable
我知道我可以用一个很好的老规则来循环。。。但是:
- 为什么它不起作用
- 我是不是误解了什么
- 我能让它按我想要的方式工作吗(除了使用正则for循环(
我的最佳猜测是HTMLCollection
不是标准数组,因此没有这样的数字索引。。。
Entries方法可用于数组。但是,getElementsByClassName
不返回数组。相反,它返回一个HTMLCollection
。您需要首先将其转换为数组。有两种方法可以做到这一点:
- 使用
Array.prototype.slice
function toArray(arr) {
return Array.prototype.slice.call(arr);
}
toArray(document.getElementsByClassName('foo'));
- 使用ES6排列
function toArray(arr) {
return [...arr];
}
toArray(document.getElementsByClassName('foo'));
getElementsByClassName
没有给出数组,但NodeList
for (const [i, foo] of [].entries.call(document.getElementsByClassName('foo')))
{
console.log(`i = ${i}, foo = `, foo);
}