使用js实现一个与数组的forEach函数一样功能的函数

在JavaScript中,forEach函数是Array的内置方法,用于遍历数组的每个元素并执行提供的函数。但是,如果你想自己实现一个与forEach功能相同的函数,可以这样做:

function myForEach(array, callback, thisArg) {
    // 检查数组是否为数组类型,如果不是则抛出错误
    if (!Array.isArray(array)) {
        throw new TypeError('myForEach() is not a function on non-array objects');
    }
    
    // 检查回调函数是否为函数类型,如果不是则抛出错误
    if (typeof callback !== 'function') {
        throw new TypeError(callback + ' is not a function');
    }
    
    // 设置thisArg,如果thisArg未定义,则默认为undefined
    thisArg = thisArg || undefined;
    
    // 使用普通的for循环来遍历数组
    for (let i = 0; i < array.length; i++) {
        // 调用回调函数,并将当前元素、当前索引和原数组作为参数传递
        // 使用.call()方法将thisArg作为回调函数的this值
        callback.call(thisArg, array[i], i, array);
    }
}

这个myForEach函数接受三个参数:一个数组、一个回调函数和一个可选的thisArg参数。它首先检查数组和回调函数是否为正确的类型,然后使用普通的for循环来遍历数组。在每次迭代中,它都会调用回调函数,并将当前元素、当前索引和原数组作为参数传递。如果提供了thisArg参数,则使用.call()方法将其作为回调函数的this值。这与Array.prototype.forEach()的行为是一致的。

下面是如何使用这个函数的示例:

const numbers = [1, 2, 3, 4, 5];

myForEach(numbers, function(value, index, array) {
    console.log(value, index, array);
    // 这将打印出每个数字、它的索引和整个数组
}, this); // thisArg是可选的,这里传递了当前的this值(通常是window对象,如果在浏览器环境中)
posted @ 2024-12-28 09:12  王铁柱6  阅读(12)  评论(0)    收藏  举报