【JS】for...in,for..of,forEach秒懂

331 阅读2分钟

本文已参与「新人创作礼」活动, 一起开启掘金创作之路。

千里之行,始于足下

for ... in

通常用来遍历一个对象所有可枚举的属性,包括继承的可枚举的属性。一般在遍历数组,字符串,普通对象时使用,不可用来遍历Map或Set对象。for...in遍历的是索引。

👇🏻栗子:

数组

别忘记数组的索引下标哦。

// 用于数组
for(let i in [1,2,3]){ 
    console.log(i) 
}
// 输出0,1,2

字符串

字符串是可迭代的。MDN链接

//字符串
for(let i in 'test'){
    console.log(i) 
}
//输出0,1,2,3

对象

for...in遍历对象的属性

//对象
for(let i in {name:'宝儿姐', sex: '女'}){
    console.log(i) 
}
// 输出 name ,sex

set对象

不可遍历set对象,输出undefined

for(let i in new Set(['张楚岚','宝儿姐','诸葛青', '宝儿姐'])){
    console.log(i)
} 
// 输出 undefined

map对象

不可遍历map对象,输出空对象

for(let i in new Map([['a', 1], ['b',2]])){
    console.log(i)
} 
// 输出{}

for ... of

用于遍历可迭代的对象,遍历对象的值。一般用于数组,字符串,Map或Set对象,但不能用于普通对象

👇🏻用法

数组

作用于数组就是遍历数组item值

for(let i of [1,2,3]){
    console.log(i) 
} // 输出 1,2,3

字符串

for(let i of 'abc'){ 
    console.log(i); 
} //输出a,b,c

普通对象

for...of不可用于遍历普通对象

for(let i of {name: '宝儿姐', sex:'女'}){
    console.log(i); 
} //Uncaught TypeError: {(intermediate value)(intermediate value)} is not iterable

set对象

for(let i of new Set([1,3,2,1])){ 
    console.log(i) 
} //输出1,3,2

map对象

for(let i of new Map([['name','宝儿姐'],['age','未知']])){
    console.log(i)
} //输出["name","宝儿姐"] ["age","未知"]

forEach

我们常用的forEach是数组的方法,别忽略了Map和Set中的forEach使用哦。

Array.prototype.forEach

数组原型的方法,不能提前中断循环

[1,2,3].forEach((item, index) => { 
    console.log(item, index)//值,索引
})

Map.prototype.forEach

Map对象的遍历的方法

(new Map([['name', '宝儿'], ['sex','女'], ['age', 'unkonw']])).forEach((i, k) => {   
    console.log(i, k)  // value , key
}) //输出 宝儿,女,unkonw

Set.prototype.forEach


new Set([1,2,4,2,1]).forEach(i => {
    console.log(i) //value
}) // 输出1,2,3

总结

1、for...in一般用来遍历对象,for...of用来遍历数组

2、字符串也是可迭代的

3、数组的forEach不能提前中断