在 for-of 循​​环中使用 entries(),遍历 HTMLCollection

Using entries() in a for-of loop, iterating over an HTMLCollection

我知道在 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 不是标准数组,因此没有数字索引...

条目方法可用于数组。但是,getElementsByClassName 不是 return 数组。相反,它 return 是 HTMLCollection。您需要先将其转换为数组。有两种方法可以做到这一点:

  1. 使用Array.prototype.slice
function toArray(arr) {
  return Array.prototype.slice.call(arr);
}

toArray(document.getElementsByClassName('foo'));
  1. 使用 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);
}