forEach는 JavaScript 배열의 함수 오류가 아닙니다.
간단한 루프를 만들려고합니다.
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
하지만 다음과 같은 오류가 발생합니다.
VM384 : 53 포착되지 않은 TypeError : parent.children.forEach는 함수가 아닙니다.
비록 parent.children
로그 :
무엇이 문제일까요?
참고 : 여기에 JSFiddle이 있습니다.
은 parent.children
객체와 같은 배열입니다. 다음 솔루션을 사용하십시오.
const parent = this.el.parentElement;
console.log(parent.children);
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
parent.children
IS의 NodeList
객체 때문에 같은 배열 인 유형 :
length
노드 수를 나타내는 속성을 포함합니다.- 각 노드는 0부터 시작하는 숫자 이름의 속성 값입니다.
{0: NodeObject, 1: NodeObject, length: 2, ...}
parent.children
배열이 아닙니다. HTMLCollection이며 forEach
메서드 가 없습니다 . 먼저 배열로 변환 할 수 있습니다. 예를 들어 ES6에서 :
Array.from(parent.children).forEach(function (child) {
console.log(child)
});
또는 스프레드 연산자 사용 :
[...parent.children].forEach(function (child) {
console.log(child)
});
parent.children
노드 목록
목록, 기술적으로는 html Collection 을 반환합니다
. 그것은 객체와 같은 배열이지만 배열이 아니므로 직접 배열 함수를 호출 할 수 없습니다. 이 컨텍스트에서이를 Array.from()
실제 배열로 변환하는 데 사용할 수 있습니다 .
Array.from(parent.children).forEach(child => {
console.log(child)
})
더 순진한 버전, 적어도 변환 및 ES6없이 모든 장치에서 작동하는지 확인하십시오.
const children = parent.children;
for (var i = 0; i < children.length; i++){
console.log(children[i]);
}
https://jsfiddle.net/swb12kqn/5/
parent.children
A는 HTMLCollection
객체 어레이 형상이다. 첫째, 메서드 Array
를 사용 하려면이를 실수로 변환해야 Array.prototype
합니다.
const parent = this.el.parentElement
console.log(parent.children)
[].slice.call(parent.children).forEach(child => {
console.log(child)
})
That's because parent.children
is a NodeList, and it doesn't support the .forEach
method (as NodeList is an array like structure but not an array), so try to call it by first converting it to array using
var children = [].slice.call(parent.children);
children.forEach(yourFunc);
There is no need for the forEach
, you can iterate using only the from
's second parameter, like so:
let nodeList = [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]
Array.from(nodeList, child => {
console.log(child)
});
If you are trying to loop over a NodeList
like this:
const allParagraphs = document.querySelectorAll("p");
I highly recommend loop it this way:
Array.prototype.forEach.call(allParagraphs , function(el) {
// Write your code here
})
Personally, I've tried several ways but most of them didn't work as I wanted to loop over a NodeList
, but this one works like a charm, give it a try!
The NodeList
isn't an Array, but we treat it as an Array, using Array.
So, you need to know that it is not supported in older browsers!
에 대한 추가 정보가 필요하십니까 NodeList
? MDN에 대한 문서를 읽으십시오 .
ES6 ( 화살표 함수 )의 기능을 사용하고 있으므로 다음 과 같이 for 루프 를 사용할 수도 있습니다 .
for(let child of [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]) {
console.log(child)
}
참고 URL : https://stackoverflow.com/questions/35969974/foreach-is-not-a-function-error-with-javascript-array
'program story' 카테고리의 다른 글
새 날짜 시간 API를 사용하여 날짜 형식 지정 (0) | 2020.08.23 |
---|---|
UIImage에서 기본 NSData 가져 오기 (0) | 2020.08.23 |
특정 문자열로 시작하는 모든 클래스 제거 (0) | 2020.08.23 |
C # 데스크톱 애플리케이션에 포함하는 데 가장 적합한 스크립팅 언어는 무엇입니까? (0) | 2020.08.23 |
자바 임베디드 데이터베이스 비교 (0) | 2020.08.23 |