准备数据
let arr = ["a","b","c","d","e"];
let obj = {
a:1,
b:2,
c:3
}
for…in
for…in 通过 key-value的形式来遍历数据
for(let val in arr){
console.log(val); //0 1 2 3 4
// console.log(arr[val]); //a b c d e
}
for(let val in obj){
console.log(val); //a b c
}
for…of
直接读取数据
for(let val of arr){
console.log(val); //a b c d e
// console.log(arr[val]); //undefind
}
for(let val of obj){
console.log(val); //bj is not iterable
}
迭代器
let obj = {
a : 1,
b: 2,
c: 3
}
console.log(Object.keys(obj));
obj[Symbol.iterator] = function(){
// 迭代协议
let values = Object.values(obj);
let index = 0;
return {
next(){ // 这里不是自定义的名称
if(index >= values.length){
return {
// value: "1", // 循环过程中的值
done: true // 代表循环是否完成
}
}else{
return{
done :false,
value: values[index++]
}
}
}
}
}
for(let val of obj){
console.log(val);
}