ale*_*nco 104 javascript ecmascript-6 vue.js
我想做一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
VM384:53未捕获的TypeError:parent.children.forEach不是函数
尽管parent.children日志:
可能是什么问题呢?
注意:这是一个JSFiddle.
Dmi*_*tin 92
这parent.children是一个类似于Array的对象.使用以下解决方案:
const parent = this.el.parentElement;
console.log(parent.children);
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
Run Code Online (Sandbox Code Playgroud)
的parent.childrenIS NodeList类型,就像对象,因为数组:
length属性,表示节点数{0: NodeObject, 1: NodeObject, length: 2, ...}请参阅本文中的更多详细信息.
mad*_*ox2 82
parent.children不是数组.它是HTMLCollection,它没有forEach方法.您可以先将其转换为数组.例如在ES6中:
Array.from(parent.children).forEach(child => {
console.log(child)
});
Run Code Online (Sandbox Code Playgroud)
或使用传播运营商:
[...parent.children].forEach(function (child) {
console.log(child)
});
Run Code Online (Sandbox Code Playgroud)
Raj*_*amy 16
parent.children将返回一个节点列表,技术上是一个html元素集合.这是一个类似于对象的数组,但不是数组,所以你不能直接调用它上面的数组函数.在此上下文中,您可以使用Array.from()它将其转换为真实数组,
Array.from(parent.children).forEach(child => {
console.log(child)
})
Run Code Online (Sandbox Code Playgroud)
Jea*_*ean 10
一个更天真的版本,至少你确定它可以在所有设备上运行,没有转换和ES6:
const children = parent.children;
for (var i = 0; i < children.length; i++){
console.log(children[i]);
}
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/swb12kqn/5/
parent.children是一个HTMLCollection类似于数组的对象.首先,您必须将其转换为真实Array使用Array.prototype方法.
const parent = this.el.parentElement
console.log(parent.children)
[].slice.call(parent.children).forEach(child => {
console.log(child)
})
Run Code Online (Sandbox Code Playgroud)
有没有必要的forEach,你可以遍历仅使用from的第二个参数,如下所示:
let nodeList = [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]
Array.from(nodeList, child => {
console.log(child)
});Run Code Online (Sandbox Code Playgroud)
如果你试图循环NodeList这样的:
const allParagraphs = document.querySelectorAll("p");
Run Code Online (Sandbox Code Playgroud)
我强烈建议以这种方式循环:
Array.prototype.forEach.call(allParagraphs , function(el) {
// Write your code here
})
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我尝试了几种方法,但大多数方法都不起作用,因为我想循环 a NodeList,但是这个方法就像一个魅力,试一试!
这NodeList不是一个数组,但是我们把它当成一个数组,使用Array.所以,你要知道旧浏览器不支持它!
需要更多信息NodeList?请阅读它关于 MDN 的文档。
那是因为它parent.children是一个NodeList,并且它不支持该.forEach方法(因为NodeList是一个类似于结构但不是数组的数组),所以尝试通过首先将它转换为数组来调用它
var children = [].slice.call(parent.children);
children.forEach(yourFunc);
Run Code Online (Sandbox Code Playgroud)