- for in 通常用来遍历对象,遍历出来的是对象的key或数组的索引index
- for of 用于可迭代对象,遍历出来的是key,例如数组,Set,Map对象,因此不能用于遍历普通对象(因为没有迭代器),如果想用for of遍历普通对象,要结合Object.keys()或使用
- forEach 通常用于遍历数组
- forEach要遍历完所有的数据, 除非抛出异常,否则没有办法停止或中断
forEach()循环。
// for in
let obj = {a:1, b:2, c:3};
for (let prop in obj) {
console.log(prop);// a b c
}
// for of
let arr = [10, 20, 30];
for (let value of arr) {
console.log(value);
}
// forEach
arr.forEach((item,index)=>{
console.log(item,index)//10 0 20 1 30 2
})