es6知识点for..of vs for...in
默认具有遍历器接口的数据结构,for of循环 当对一个数据结构使用for of循环遍历的时候,会自动调用遍历器接口。 ES6中有四类数据结构默认具有遍历器接口: (1)数组 (2)某些类数组 (3)Map (4)Set
for of 遍历
var arr = [1,2,3,4,5,6];
//不同循环遍历
for(let i = 0;i<arr.length;i++){
console.log(arr[i]);
}
arr.forEach(i=>{
console.log(i);
});
//用迭代器遍历
let iterator = arr[Symbol.iterator]();
let result =iterator.next();
while(!result.done){
console.log(result.value);
resulf = iterator.next();
}
//for of 遍历
//array
for(let item of arr){
console.log(item);
}
//set
let s = new Set(["a","b","c"]);
for(let item of s){
console.log(item);
}
//map
let m = new Map([["name","姜姜"],["age",23]]);
for(let item of m){
console.log(item);
}
for in
let obj = {x:1,y:2,z:3};
let arr = ["a","b","c"];
for(let key in obj){
console.log(key);
console.log(obj[key]);
}
for(let key in arr){
console.log(key);
console.log(arr[key]);
}