前端 - 遍历(map/forEach/for...of/for...in)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/kelly0721/article/details/102767706

遍历分为遍历对象和遍历数组,又可以分为遍历键值和遍历值

首先,map()和forEach()是Array自带的方法,Map对象也有forEach()方法,而for…in和for…of是对数组/类数组元素进行for循环操作的方法。
也就是说,在使用map()和forEach()的时候,需要用数组调用
map()和forEach()包含的匿名函数都是三个参数(item,index,input)(当前项,当前项的索引,原始数组)

1. map方法

map只能遍历数组,不能遍历对象
map 遍历的时候必须要有 return
如果数组本身是普通对象(如,number、string等)那么即使在 map中做了改变自己属性的操作也是无法生效的,如果数组本身是个对象,那么被改变的属性就会在原对象中生效

const arr = [11, 12, 13];
const b = arr.map(i => {
	console.log(i);
	return i*2;
})
console.log(arr,b);
// arr = [11, 12, 13];
// b = [22, 24, 26];
const arr = [{t: 1}, {t: 2}];
const b = arr.map(i => {
	const newObj = i;
	newObj.t = newObj.t*2;
	return newObj;
})
console.log(arr,b);
// arr = [{t: 2}, {t: 4}];
// b = [{t: 2}, {t: 4}];

2. forEach方法

forEach只能遍历数组,不能遍历对象
没有return属性,只有循环的作用,不能改变原先对象的属性,相当于 for() 循环

const arr = [11, 12, 13];
const b = arr.forEach(i => {
	return i*2;
})
console.log(arr,b);
// arr = [11, 12, 13];
// undefined

3. for…of 方法

forEach只能遍历数组,不能遍历对象
只有循环的作用,不能改变原先对象的属性
for of 不同于 forEach, 它可以与 break、continue和return 配合使用,也就是说 for of 循环可以随时退出循环
如果对象也想用该方法遍历, 可以使用 Object.keys() 获取对象的 key值集合后,再使用 for of

const arr = [11, 12, 13];
for (let i of arr) {
    console.log(i);
}
// 11, 12, 13
const arr = {a: 11, b: 12, c: 13}
for (let i of Object.keys(arr) {
    console.log(i)
}
// 11, 12, 13

4. for…in 方法

这个方法也是一个遍历的方法,和上面三种不一样的是,他不是遍历值,他是遍历键值,即属性名
如果是数组,则返回下标,如果是对象,则返回对象的键值
for in 循环会以任意顺序遍历键名

const arr = [11, 12, 13];
for (let i in arr) {
    console.log(i);
}
// 0, 1, 2
const arr = {a: 11, b: 12, c: 13};
for (let i in arr) {
    console.log(i);
}
//a, b, c

猜你喜欢

转载自blog.csdn.net/kelly0721/article/details/102767706