program story

forEach는 JavaScript 배열의 함수 오류가 아닙니다.

inputbox 2020. 8. 23. 09:08
반응형

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.childrenIS의 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.childrenA는 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

반응형