JavaScript中forEach和map的区别及实现

本文详细介绍了JavaScript中map和forEach两种数组遍历方法的区别。map方法不会直接修改原数组,而是返回一个新的数组;forEach则可以改变原数组。此外,map有返回值,而forEach无返回值。在错误处理上,两者都需要通过try...catch...来中断,而不能用return。文中还提供了map和forEach的实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

区别

  1. map不能修改原数组,forEach能改变原数组
  2. map返回值,创建新数组,而forEach返回值,返回结果undefined
  3. map和forEach用只能用try...catch...中断抛出错误中断,而return不能,用其效果相当于for循环的continue会跳过此次循环进入下一次循环。

实现

  • forEach方法实现
Array.prototype.forEach = function (callback, context) {
    // 不能是null调用方法
    if (this === null) {
        throw new TypeError(
            "Array.prototype.forEach" + "called on null or undefined"
        );
    }
    // 第一个参数必须要为function
    if (typeof callback !== "function") {
        throw new TypeError(callback + " is not a function");
    }
    // 获取原数组,因为会改变原数组
    let arr = this;
    let len = arr.length;
    //
    for (let i = 0; i < len; i++) {
        callback.call(context, arr[i], i, arr);
    }
    // 数组没有返回值的,不用返回
}
  • map实现:
Array.prototype.map = function (callback, context) {
    // 不能是null调用方法
    if (this === null) {
        throw new TypeError(
            "Array.prototype.map" + "called on null or undefined"
        );
    }
    // 第一个参数必须要为function
    if (typeof callback != 'function') {
        throw new TypeError(
            callback + 'is not a function'
        )
    }
    // 利用slice方法浅拷贝一下
    let arr = Array.prototype.slice.call(this)
    let len = arr.length
    let arrMap = []
    for (let i = 0; i < len; i++) {
        arrMap[i] =  callback.call(context, arr[i], i, arr)
    }
    return arrMap
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

影风莫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值