Skip to content

Latest commit

 

History

History

2804.Array Prototype ForEach

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

English Version

题目描述

编写一个数组方法 forEach,使其可以在任何数组上调用 array.forEach(callback, context) 方法,它将在数组的每个元素上执行回调函数。forEach 方法不应该返回任何内容。

回调函数 callback 接受以下参数:

  • value - 表示数组中当前正在处理的元素的值。
  • index - 表示数组中当前正在处理的元素的索引。
  • array - 表示数组本身,在回调函数内部可以访问整个数组。

上下文 context 应该是作为函数上下文参数传递给回调函数的对象,确保回调函数内部的 this 关键字引用此上下文对象。

尝试在不使用内置数组方法的情况下实现这个方法。

 

示例 1:

输入:
arr = [1,2,3], 
callback = (val, i, arr) => arr[i] = val * 2, 
context = {"context":true}
输出:[2,4,6]
解释:
arr.forEach(callback, context)  
console.log(arr) // [2,4,6]

回调函数在数组的每个元素上执行。

示例 2:

输入:
arr = [true, true, false, false], 
callback = (val, i, arr) => arr[i] = this, 
context = {"context": false}
输出:[{"context":false},{"context":false},{"context":false},{"context":false}]
解释:
arr.forEach(callback, context) 
console.log(arr) // [{"context":false},{"context":false},{"context":false},{"context":false}]

回调函数在数组的每个元素上以正确的上下文执行。

示例 3:

输入:
arr = [true, true, false, false], 
callback = (val, i, arr) => arr[i] = !val, 
context = {"context": 5}
输出:[false,false,true,true]

 

提示:

  • arr 是一个有效的 JSON 数组
  • context 是一个有效的 JSON 对象
  • fn 是一个函数
  • 0 <= arr.length <= 105

解法

TypeScript

Array.prototype.forEach = function (callback: Function, context: any): void {
    for (let i = 0; i < this.length; ++i) {
        callback.call(context, this[i], i, this);
    }
};

/**
 *  const arr = [1,2,3];
 *  const callback = (val, i, arr) => arr[i] = val * 2;
 *  const context = {"context":true};
 *
 *  arr.forEach(callback, context)
 *
 *  console.log(arr) // [2,4,6]
 */