DAY 28
0
Modern Web

## 哪些可以迭代?

ArraySetMapString

## 使用:一般物件

``````let obj = {
name: 'wendy',
age: 18,
[Symbol.iterator]: '勵志成為迭代物件',
};
for (let x of obj) {
console.log(x);
}

//TypeError: obj is not iterable
``````

## 使用陣列

``````let myArray = ['wendy', 20, 30];
for (let x of myArray) {
console.log(x);
}
//wendy
//20
//30
``````

## 開始介紹他們

• iterable object 可迭代物件: Array、 Set、 Map (可迭代的型別)

• iterator object 迭代器物件 （自己本身可以迭代）

• iteration object 迭代結果物件 （存放迭代每步驟的結果

### 可迭代物件( iterable object)

``````let myArray = [10, 20];
let myArrayIterator = myArray[Symbol.iterator]();
console.log(myArrayIterator); //Object [Array Iterator] {}
let mySet = new Set([1, 2]);
console.log(mySet[Symbol.iterator]()); //[Set Iterator] { 1, 2 }

let myMap = new Map([
[1, 'wendy'],
[2, 'nick'],
['red', 'apple'],
]);
console.log(myMap[Symbol.iterator]()); //[Map Entries] { [ 1, 'wendy' ], [ 2, 'nick' ], [ 'red', 'apple' ] }

let myNumber = 10;
console.log(myNumber[Symbol.iterator]); //undefined
let myObj = { 1: 'wendy', 2: 'ann' };
console.log(myObj[Symbol.iterator]); //undefined

``````

### 迭代器物件 iterator object

`myArray[Symbol.iterator]()`

### 迭代結果物件 iteration object

``````{
value:xxx,
done:false
}
``````

``````let myArray = [10, 20];
let myIterator = myArray[Symbol.iterator]();
console.log(myIterator.next());//{ value: 10, done: false }
console.log(myIterator.next());//{ value: 20, done: false }
console.log(myIterator.next());//{ value: undefined, done: true }
``````

## 如何做出可迭代物件

``````let obj = {
name: 'wendy',
age: 18,
goal: '勵志成為迭代物件',
};
for (let x of obj) {
console.log(x);
}

//TypeError: obj is not iterable

``````

1.要有 next()
2.要有一個物件 {next:xxx,done:true/false}

``````let myObj = {
name: 'wendy',
age: 18,
hair: 'black',
[Symbol.iterator]: function () {
let index = 0;
let values = Object.values(this);
return {
next: () => ({ value: values[index++],
done: index > values.length }),
};
},
};

let iterator = myObj[Symbol.iterator]();
console.log(iterator.next());//{ value: 'wendy', done: false }
console.log(iterator.next());//{ value: 18, done: false }
console.log(iterator.next());//{ value: 'black', done: false }
console.log(iterator.next());//{ value: undefined, done: true }

for (let y of myObj) {
console.log(y);
}
//wendy
//18
//black
``````

``````function* animal() {
yield 100;
yield 200;
yield 'wendy';
}

let genAnimal = animal();
console.log(genAnimal.next().value); //100
console.log(genAnimal.next().value); //200
console.log(genAnimal.next().value); //wendy
console.log(genAnimal.next().value); //undefined

for (x in genAnimal) {
console.log(x);
}
//100
//200
//wendy
//undefined
``````

JavaScript大全第七版
mdn
A Simple Guide to ES6 Iterators in JavaScript with Examples

### 1 則留言

0
juck30808
iT邦新手 3 級 ‧ 2021-10-14 12:32:26

wendy iT邦新手 5 級 ‧ 2021-10-14 19:16:12 檢舉