格式: for(let k of xx) 獲取的是選項值、for...in獲取的索引
{
let arr = ['a','b','c'];
for(let key of arr){
console.info(key);// a b c
}
}
{
let arr = ['a','b','c'];
for(let key in arr){
console.info(key);//0 1 2
}
}
{
let set1 = new Set(['j','k','l']);
for(let key of set1){
console.info(key);//j k l
}
}
但對象默認無法用for...of遍歷,如
{
let obj = {
a:1,
b:2
}
for(let k of obj){
console.info(k);
//報錯 Uncaught TypeError: obj[Symbol.iterator] is not a function
}
}
二、Iterator(遍歷器)
意義:Iterator接口的目的,就是爲所有數據結構,提供了一種統一的訪問機制
數組默認就有Symbol.iterator屬性,所以可以直接使用
{
let arr = ['aa','bb','cc'];
let iter = arr[Symbol.iterator]();//數組默認就有Symbol.iterator屬性
console.info(iter.next());//{value: "aa", done: false}
console.info(iter.next());//{value: "bb", done: false}
console.info(iter.next());//{value: "cc", done: false}
console.info(iter.next());//{value: undefined, done: true}
}
對象自定義Symbol.iterator屬性
//對象部署Symbol.iterator屬性
{
let obj = {
a:['a','b','c','d'],
[Symbol.iterator](){
let index = 0;
let len = this.a.length;
let arr = this.a;
return {
next(){
if(index<len){
return {
value:arr[index++],
done:false
}
}else{
return {
value:undefined,
done:true
}
}
}
}
}
}
for(let k of obj){
console.log(k);//a b c d
}
}
自定義2
{
let obj = {
start:[1,3,2],
end:[7,9,8],
[Symbol.iterator](){
let self = this;
let index = 0;
//結合數組
let arr = self.start.concat(self.end);
console.info(arr)
//數組大小
let length = arr.length;
console.info(length)
//返回閉包
return {
next(){
if (index < length){
return {
value:arr[index++],
done:false
}
}else{
return{
value:arr[index++],
done:true
}
}
}
}
}
};
for(let key of obj){
console.log(key)
}
}