var array = [1, 2, 3, 4, 6, 6, 6, 6, 6];
array[Symbol.iterator] = (function() {
var current = 0;
console.log('executed')
var iterator = {
next: function() {
var iteratorObject = {
done: "undefined",
value: false
};
//returns the next item in the sequence
if (current != this.length) {
iteratorObject.done = this[current];
current++;
//return false
return iteratorObject;
} else if (current === this.length) {
//finished
//return true
iteratorObject.done = "undefined";
iteratorObject.value = true;
return iteratorObject;
} else {
console.log('something broke!')
}
}
}
return iterator;
})();
在上面的代码中,我正在为我创建的数组对象编写一个自定义迭代器。但是,它一直对数组使用内置的Symbol.iterator,为什么会这样呢?
您可以说它运行的是内置迭代器,而不是我创建的自定义迭代器?
答案 0 :(得分:2)
这是您出问题的地方
array.[Symbol.iterator]
-您的console.log
证明您确实拥有for(i of array)
抛出错误Uncaught TypeError: array is not iterable
,因为您的代码错误done
返回的内容交换了value
和next()
的含义value
应该是值undefined
,而不是字符串"undefined"
array[Symbol.iterator]
必须是一个函数-但由于最后一个Object
()
解决所有问题,您会得到
var array = [1, 2, 3, 4, 6, 6, 6, 6, 6];
array[Symbol.iterator] = function() {
let current = 0;
return {
next: () => {
if (current != this.length) {
return { value: this[current++], done:false };
} else if (current === this.length) {
return {value:undefined, done:true};
} else {
console.log('something broke!')
}
}
};
};
for(let i of array) {
console.log(i);
}