数组操作forEach和map

forEach和map的相同点

1、都是循环遍历数组中的每一项
2、入参匿名函数都支持三个参数,当前项item,当前项索引index,原始数组arr;匿名函数中的this都指向window
3、都可以通过return跳过本次循环
4、都无法通过使用 break 语句来中断循环。 break 语句用于中断循环的功能只适用于 for 循环或 while 循环
5、可以用try catch包裹实现跳出循环

第3点代码实现

const array1 = [1, 2, 3, 4, 5];
        let sum1 = 0;

        array1.forEach((element) => {
            if (element === 3) {
                return; // 跳过本次循环
            }
            console.log(element); //1,2,4,5
            sum1 += element;
        });

        console.log(sum1); // 输出: 12
const array1 = [1, 2, 3, 4, 5];
let arr4 =array1.map((element) => {
     if (element === 3) {
         return //跳过本次循环
     }
     console.log(element); //1,2,4,5
     return element+1
 });

 console.log(arr4); // 输出: [2,3,undefined,5,6]

第5点代码实现

let arr2 = [0, 1, "stop", 3, 4];
try {
    arr2.forEach(element => {
        if (element === "stop") {
            throw new Error("forEachBreak");
        }
        console.log(element); // 输出 0 1 后面不输出
    });
} catch (e) {
    console.log(e.message); // forEachBreak
};
let arr2 = [0, 1, "stop", 3, 4];
try {
    arr2.map(element => {
        if (element === "stop") {
            throw new Error("forEachBreak");
        }
        console.log(element); // 输出 0 1 后面不输出
    });
} catch (e) {
    console.log(e.message); // forEachBreak
};

forEach和map的区别

1、map有返回值,会分配内存空间。返回一个和原数组长度一致的新数组,可以进行链式操作;forEach没有返回值,无法进行链式调用

是否改变原始数组

基础数据类型
forEach不会改变

const array = [1, 2, 3, 4];
array.forEach(item => {
    item = item + 1
})
console.log(array); // [1,2,3,4]

map不会改变

const array = [1, 2, 3, 4];
array.map(item => {
    item = item + 1
})
console.log(array); // [1,2,3,4]

引用数据类型
forEach会改变

        const arr = [{
            name: 'shaka',
            age: 23
        }, {
            name: 'virgo',
            age: 18
        }]
        arr.forEach(item => {
            if (item.name === 'shaka') {
                item.age = 100
            }
        })
        console.log(arr); //[{name: 'shaka', age: 100}, {name: 'virgo', age: 18}]

map会改变

        const arr = [{
            name: 'shaka',
            age: 23
        }, {
            name: 'virgo',
            age: 18
        }]
        arr.map(item => {
            if (item.name === 'shaka') {
                item.age = 100
            }
        })
        console.log(arr); //[{name: 'shaka', age: 100}, {name: 'virgo', age: 18}]

结论:如果操作数组项item改变,对于数组项目是基础数据类型的,forEach和map都不会改变原数组;对于数组项目是引用数据类型的,forEach和map都会改变原数组;
数组项目是基础数据类型的可以通过遍历+访问数组下标来改变原始数组

const array = [1, 2, 3, 4];
array.forEach((item,index) => {
    array[index] = item + 1
})
console.log(array); // [2,3,4,5]

const array = [1, 2, 3, 4];
array.map((item,index) => {
    array[index] = item + 1
})
console.log(array); // [2,3,4,5]

参考:
链接: link

链接: link

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值