각각은 JavaScript 배열의 함수 오류가 아님
난 간단한 루프를 만들려고 한다.
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
그러나 나는 다음과 같은 오류를 얻는다.
VM384:53 Uncaused TypeError: parent.children.각자는 함수가 아님
그럼에도 불구하고.parent.children로그:
뭐가 문제야?
주: 여기 JSFiddle이 있다.
첫 번째 옵션: 각각에 대해 간접 호출
그parent.children배열과 같은 객체.다음 솔루션을 사용하십시오.
const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
그parent.children이다NodeList형식, 즉 다음과 같은 이유로 배열과 같은 개체:
- 그것에는 다음이 포함되어 있다.
length노드 수를 나타내는 속성 - 각 노드는 0부터 시작하는 숫자 이름을 가진 속성 값이다.
{0: NodeObject, 1: NodeObject, length: 2, ...}
자세한 내용은 이 문서에서 확인하십시오.
두 번째 옵션: 반복 가능한 프로토콜 사용
parent.children이다HTMLCollection: 반복 가능한 프로토콜을 구현한다.ES2015 환경에서는HTMLCollection어떤 건축물이든 반복적으로 받아들여질 수 있다.
사용하다HTMLCollection스프레드 오퍼레이터 사용:
const parent = this.el.parentElement;
[...parent.children].forEach(child => {
console.log(child);
});
아니면...for..of사이클(내가 선호하는 옵션):
const parent = this.el.parentElement;
for (const child of parent.children) {
console.log(child);
}
parent.children배열이 아니다.그것은 HTMLCollection이고 그것은 없다.forEach방법의먼저 배열로 변환할 수 있다.예를 들어 ES6:
Array.from(parent.children).forEach(child => {
console.log(child)
});
또는 스프레드 연산자 사용:
[...parent.children].forEach(function (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답례하다
노드 목록 목록, 기술적으로 html 모음입니다.그것은 개체와 같은 배열이지만 배열은 아니기 때문에 배열 함수를 직접 호출할 수는 없다.이 컨텍스트에서 사용할 수 있음Array.from()그걸 진짜 배열로 바꾸려면
Array.from(parent.children).forEach(child => {
console.log(child)
})
parent.childrena이다HTMLCollection그것은 배열과 같은 물체다.첫째로, 당신은 그것을 진짜로 변환해야 한다.Array사용하다Array.prototype방법들
const parent = this.el.parentElement
console.log(parent.children)
[].slice.call(parent.children).forEach(child => {
console.log(child)
})
는 필요 없으며, 의 두 번째 매개 변수만 사용하여 반복할 수 있다.
let nodeList = [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]
Array.from(nodeList, child => {
console.log(child)
});
각각에 대해 올바르게 입력했는지 확인할 수 있으며, 다른 프로그래밍 언어에서처럼 poreach를 입력하면 작동하지 않는다.
만약 당신이 반복하려고 한다면NodeList다음과 같은 경우:
const allParagraphs = document.querySelectorAll("p");
나는 이런 식으로 반복할 것을 강력히 추천한다.
Array.prototype.forEach.call(allParagraphs , function(el) {
// Write your code here
})
개인적으로 여러 가지 방법을 시도해 보았지만 대부분 반복적으로 반복하고 싶어 효과가 없었다.NodeList하지만이건 매력적으로 작동해봐,한번 해봐!
그NodeList배열은 아니지만, 우리는 그것을 배열로 취급한다.Array.따라서, 여러분은 그것이 오래된 브라우저에서 지원되지 않는다는 것을 알아야 한다!
에 대한 자세한 정보 필요NodeList? MDN에 대한 설명서를 읽어 보십시오.
그 이유는parent.childrenNodeList는 NodeList이며, 이 목록은 지원하지 않는다..forEach메서드(NodeList는 구조와 유사하지만 배열은 아니기 때문에) 먼저 다음을 사용하여 구조물을 배열로 변환하여 호출하십시오.
var children = [].slice.call(parent.children);
children.forEach(yourFunc);
ES6(화살표 기능)의 기능을 사용하고 있으므로 다음과 같은 루프를 간단히 사용할 수도 있다.
for(let child of [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]) {
console.log(child)
}
JSON.parse()를 사용한다.
str_json = JSON.parse(array);
str_json.forEach( function(item, index) {
console.log(item)
}
사용할 수 있다childNodes대신에childrenchildNodes또한 브라우저 호환성 문제를 고려할 때 더 신뢰할 수 있으며, 자세한 내용은 다음 웹 사이트를 참조하십시오.
parent.childNodes.forEach(function (child) {
console.log(child)
});
또는 스프레드 연산자 사용:
[...parent.children].forEach(function (child) {
console.log(child)
});
참조URL: https://stackoverflow.com/questions/35969974/foreach-is-not-a-function-error-with-javascript-array
'IT이야기' 카테고리의 다른 글
| Nuxt.js vuex 스토어가 유지되지 않음 (0) | 2022.03.27 |
|---|---|
| 관찰 가능한 테이크아웃 취소작동하지 않을 때까지 (0) | 2022.03.27 |
| 페이지를 로드하는 동안 VueJS 구문을 숨기려면 어떻게 해야 하는가? (0) | 2022.03.27 |
| POST 요청을 보내는 방법? (0) | 2022.03.27 |
| Vue 3 및 Typecript - 메서드에서 데이터 속성에 액세스할 수 없음 (0) | 2022.03.27 |
