배열이 있고 기본 반복기 동작을 재정의했습니다. 문제는 재정의 한 후 반환 된 반복기가 반복 할 수 없게되고 for..of..loop가 실패하지만 배열에서 작동하지만 배열의 반복기 next () 메서드에 대한 명시 적 호출은 여전히 작동한다는 것입니다. 다음은 아래 코드입니다.
let arr = ["A", "B", "C", "D", "E", "F"];
arr[Symbol.iterator] = function(){
let i = 0;
return {
//Iterator interface
next:function(){
//IteratorResult Interface
return {
value: arr[i++]+"..",
done: arr[i] == undefined?true:false
}
}
}
}
그리고 여기에 반복기 객체가 있습니다.
let arrIterator = arr[Symbol.iterator](); //An iterator object returned but not iterable
반복기 객체에서 for..of..loop를 사용한 소비 시험
for (let i of arrIterator){
console.log(i);
}
산출
배열에서 for..of..loop를 사용한 소비 평가판
for (let i of arr){
console.log(i);
}
산출
명시적인 next () 메서드 호출을 사용한 소비 시도
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
산출
for..of..loop 소비에 대해 사용자 지정 반복기를 반복 가능하게 만드는 방법을 정말로 알고 싶습니다 .
감사
당신은 (뿐만 아니라의 Iterable 프로토콜을 구현해야하는 대신 반복자의 )
[Symbol.iterator]: function() { return this; }
Iterator 개체에 추가 하면 작동합니다.
let arr = ["A", "B", "C", "D", "E", "F"];
arr[Symbol.iterator] = function() {
let i = 0;
return {
//Iterator interface
next: function() {
//IteratorResult Interface
return {
value: arr[i++] + "..",
done: arr[i] == undefined ? true : false
}
},
// Iterable interface
[Symbol.iterator]: function() {
return this;
}
}
}
let arrIterator = arr[Symbol.iterator](); //An iterator object returned but not iterable
for (let i of arrIterator) {
console.log(i);
}
자세한 정보는 반복 프로토콜 을 참조하십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다