返回介绍

solution / 2800-2899 / 2804.Array Prototype ForEach / README_EN

发布于 2024-06-17 01:02:59 字数 3559 浏览 0 评论 0 收藏 0

2804. Array Prototype ForEach

中文文档

Description

Write your version of method forEach that enhances all arrays such that you can call the array.forEach(callback, context) method on any array and it will execute callback on each element of the array. Method forEach should not return anything.

callback accepts the following arguments:

  • currentValue - represents the current element being processed in the array. It is the value of the element in the current iteration.
  • index - represents the index of the current element being processed in the array.
  • array - represents the array itself, allowing access to the entire array within the callback function.

The context is the object that should be passed as the function context parameter to the callback function, ensuring that the this keyword within the callback function refers to this context object.

Try to implement it without using the built-in array methods.

 

Example 1:

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

The callback is executed on each element of the array.

Example 2:

Input: 
arr = [true, true, false, false], 
callback = (val, i, arr) => arr[i] = this, 
context = {"context": false}
Output: [{"context":false},{"context":false},{"context":false},{"context":false}]
Explanation: 
arr.forEach(callback, context) 
console.log(arr) // [{"context":false},{"context":false},{"context":false},{"context":false}]

The callback is executed on each element of the array with the right context.

Example 3:

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

 

Constraints:

  • arr is a valid JSON array
  • context is a valid JSON object
  • fn is a function
  • 0 <= arr.length <= 105

Solutions

Solution 1

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]
 */

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文