xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

如何使用 js 实现一个类似数组的 forEach 的原型方法 All In One

如何使用 js 实现一个类似数组的 forEach 的原型方法 All In One

Array.prototype.forEach

// Arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function (element) { /* … */ })
forEach(function (element, index) { /* … */ })
forEach(function (element, index, array) { /* … */ })
forEach(function (element, index, array) { /* … */ }, thisArg)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

question

Array.prototype.myForEach


Array.prototype.myForEach = function (visitors, context) {
  // 实现
}

// 测试用例
const nums = [1, 2, 3];
nums.myForEach(function(a, b, c, thisObj) {
  console.log(`a, b, c =`, a, b, c);
});

// a, b, c = 1 0 [ 1, 2, 3 ]
// a, b, c = 2 1 [ 1, 2, 3 ]
// a, b, c = 3 2 [ 1, 2, 3 ]

const strs = ['a', 'b', 'c'];
strs.myForEach(function(item, index, arr, thisObj) {
  console.log(`this.title, index, arr =`, this.title + item);
}, {title: 'JS: '});

// this.title, index, arr = JS: a
// this.title, index, arr = JS: b
// this.title, index, arr = JS: c



solution

Array.prototype.myForEach

  1. JavaScript version
"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-02-22
 * @modified
 *
 * @description 如何使用 js 实现一个类似数组的 forEach 的原型方法 myForEach
 * @description
 * @difficulty Medium
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/17146458.html
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

// export {};

const log = console.log;

// 参考
// forEach(function (element, index, array) { /* … */ }, thisArg)

// ES5 function ✅, ES6 Arrow function ❌
Array.prototype.myForEach = function (visitors, context) {
  // 实现
  // prototype 使用 this 指向调用方,即这里数组
  console.log(`\nthis =`, this);
  const arr = [...this];
  // console.log(`visitors, context =`, visitors, context);
  for (let i = 0; i < arr.length; i++) {
    // console.log(`arr[i] =`, arr[i]);
    // ✅
    // visitors(arr[i], i, arr);
    // 改变 this 指向
    // 调用 apply, call 会立即执行;调用 bind 不会立即执行
    if(context) {
      // apply 参数数组 (this, [a1, a2, a3, ..., aN])
      visitors.apply({...this, ...context}, [arr[i], i, arr, this]);
      // const thisObj = {...this, ...context};
      // visitors.apply(thisObj, [arr[i], i, arr, thisObj]);
      // visitors.apply({...this, ...context}, [arr[i], i, arr, {...this, ...context}]);
    } else {
      // call 参数列表 (this, a1, a2, a3, ..., aN)
      visitors.call(this, arr[i], i, arr, this);
    }
  }
}


const nums = [1, 2, 3];
nums.myForEach(function(a, b, c, thisObj) {
  console.log(`a, b, c =`, a, b, c);
  // console.log(`thisObj =`, thisObj);
});

// a, b, c = 1 0 [ 1, 2, 3 ]
// a, b, c = 2 1 [ 1, 2, 3 ]
// a, b, c = 3 2 [ 1, 2, 3 ]

const strs = ['a', 'b', 'c'];
strs.myForEach(function(item, index, arr, thisObj) {
  console.log(`this.title, index, arr =`, this.title + item);
  // console.log(`index, arr =`, index, arr);
  // console.log(`thisObj =`, thisObj);
}, {title: 'JS: '});

// this.title, index, arr = JS: a
// this.title, index, arr = JS: b
// this.title, index, arr = JS: c



// $ npx ts-node ./prototype.myForEach.js


  1. TypeScript version
"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-02-22
 * @modified
 *
 * @description 如何使用 js 实现一个类似数组的 forEach 的原型方法 myForEach
 * @description
 * @difficulty Medium
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/17146458.html
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

// export {};

const log = console.log;

// 参考
// interface Array<T> {
//   forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
// }

// interface Array<T> {
//   myForEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
// }

declare interface Array<T> {
  myForEach(callbackfn: (value: T, index: number, array: T[], thisObj: T) => void, thisArg?: any): void;
  // myForEach(callbackfn: function(item: T, i: number, arr: T[], thisObj: typeof callbackfn): void, thisArg?: any): void;
}



// 参考
// forEach(function (element, index, array) { /* … */ }, thisArg)

// ES5 function ✅, ES6 Arrow function ❌
Array.prototype.myForEach = function (visitors, context) {
  // 实现
  // prototype 使用 this 指向调用方,即这里数组
  console.log(`\nthis =`, this);
  const arr = [...this];
  for (let i = 0; i < arr.length; i++) {
    // 改变 this 指向
    // 调用 apply, call 会立即执行;调用 bind 不会立即执行
    if(context) {
      // apply 参数数组 (this, [a1, a2, a3, ..., aN])
      visitors.apply({...this, ...context}, [arr[i], i, arr, this]);
    } else {
      // call 参数列表 (this, a1, a2, a3, ..., aN)
      visitors.call(this, arr[i], i, arr, this);
    }
  }
}


const nums = [1, 2, 3];
nums.myForEach(function(this: any, a, b, c, thisObj) {
  // A 'this' parameter must be the first parameter.ts(2680) ✅
  console.log(`a, b, c =`, a, b, c);
  console.log(`thisObj =`, thisObj);
  // console.log(`this =`, nums);
  console.log(`this = `, this);
});

// const nums = [1, 2, 3];
// nums.myForEach(function(a, b, c, thisObj) {
//   // A 'this' parameter must be the first parameter.ts(2680) ✅
//   console.log(`a, b, c =`, a, b, c);
//   console.log(`thisObj =`, thisObj);
//   // console.log(`this =`, nums);
//   console.log(`this = `, this);
// });

// a, b, c = 1 0 [ 1, 2, 3 ]
// a, b, c = 2 1 [ 1, 2, 3 ]
// a, b, c = 3 2 [ 1, 2, 3 ]

const strs = ['a', 'b', 'c'];
strs.myForEach(function(this: any, item, index, arr, thisObj) {
  // 断言 this as {};
  console.log(`this.title, index, arr =`, this.title + item);
  console.log(`this =`, this);
  console.log(`thisObj =`, thisObj);
}, {title: 'JS: '});

// this.title, index, arr = JS: a
// this.title, index, arr = JS: b
// this.title, index, arr = JS: c



// $ npx ts-node ./prototype.myForEach.ts



image

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-02-22 23:51  xgqfrms  阅读(89)  评论(1编辑  收藏  举报