javascript - 为什么 forEach 不适用于 child ?

标签 javascript for-loop foreach parent-child

我有一个<div>和一些 child <div>在里面。例如

<div id="niceParent">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

我尝试使用 forEach 循环遍历它们函数,因为我认为 document.getElementById("niceParent").children是一个数组,因为我可以使用

访问元素
console.log(document.getElementById("niceParent").children[1]);
console.log(document.getElementById("niceParent").children[2]);
console.log(document.getElementById("niceParent").children[3]);
console.log(document.getElementById("niceParent").children[4]);

因此我尝试了

document.getElementById("niceParent").children.forEach(function(entry) {
  console.log(entry);
});

这不起作用。我明白

TypeError: document.getElementById(...).children.forEach is not a function

作为一种解决方法,我还尝试了一个(更复杂的)for..in循环:

for (var i in document.getElementById("niceParent").children) {
  if (document.getElementById("niceParent").children[i].nodeType == 1) console.log(document.getElementById("niceParent").children[i]);
}

按预期工作。

为什么?

最佳答案

因为 .children 包含 HTMLCollection [MDN] ,不是数组。 HTMLCollection 对象是一个类似数组的对象,它公开 .length 属性并具有数字属性,就像> 数组,但它不是从 Array.prototype 继承的,因此不是数组。

您可以使用Array.prototype.slice将其转换为数组:

var children = [].slice.call(document.getElementById(...).children);
<小时/>

ECMAScript 6 引入了一个新的 API,用于将迭代器和类似数组的对象转换为真正的数组:Array.from [MDN] 。如果可能的话使用它,因为它使意图更加清晰。

var children = Array.from(document.getElementById(...).children);

关于javascript - 为什么 forEach 不适用于 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15094886/

相关文章:

arrays - Bash 数组保存

java - 在java中编写一个连续的 'for'循环

php - 无法弄清楚 foreach 循环

Java实现Iterable,对于每个和方法

javascript - JavaScript 中的选择器

javascript - console.log 不会打印 Node js 中的所有快速 session 属性

javascript - 重新加载后显示 toast 通知

javascript - 在同一函数(NodeJs)中停止多个 setInterval

r - for 循环与 ggplots 生成具有相同值但不同标题的图形

javascript - 用不同的值填充数组的数组