一個數據結構只要部署了Symbol.iterator屬性就能使用 for...of遍歷 與 ...運算符 操作
Object身上沒有Symbol.iterator,當直接使用時會報錯
let obj = {
0: 'a',
1: 'b',
2: 'c',
}
console.log([...obj])//報錯obj is not iterable
在沒有Symbol.iterator方法下運行
let obj = {
0: 'a',
1: 'b',
2: 'c',
}
for(let p of obj){
console.log(p);//TypeError: obj is not iterable
}
Array身上天生具備Symbol.iterator
let arr = [1,2,3,4];
console.log([...arr]);//(4) [1, 2, 3, 4]
數組,天生具備Symbol.iterator方法所以可以使用
而我們Object需要用到...運算符 與 for of遍歷怎么辦呢
如果我們要使用它的話,Object身上需要有一個Symbol.iterator屬性代碼如下:
let obj = {
0: 'a',
1: 'b',
2: 'c',
length: 3,
[Symbol.iterator]: function () {
// index用來記遍歷圈數
let index = 0;
let next = () => {
return {
value: this[index],
done: this.length == ++index
}
}
return {
next
}
}
}
// console.log(obj.length)
console.log([...obj]);//(2) ["a", "b"]
for(let p of obj){
console.log(p) //"a" "b"
}
