当前位置:网站首页>JS array foreach source code parsing

JS array foreach source code parsing

2022-07-07 15:48:00 Sam young

//  The original method 
(method) Array<number>.forEach(callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any): void
  • notice forEach The first parameter in is callbackfn : The callback method , You can put value,index,list Return all to callbackfn Method inside .
const list = ['a', 'b', 'c', 'd'];
//  Be careful not to use  => (fn) {...}  How to write it , because this The object will not be found 
// item:  Return the value of each array 
// index:  Return the index corresponding to the array  0 1 2....
// array:  Return the array itself of the loop 
Array.prototype.newForEach = function (fn: (item: any, index: number,array: any[]) => void) {
    
  console.log(this); //  there this Will point to  list - ['a', 'b', 'c', 'd']
  const len = this.length;
  for (let i = 0; i < len; i++) {
    
    //  Pass the element to the callback function 
    fn(this[i], i,this);
  }
};
list.newForEach((item, index) => {
    
  console.log(item, index);
});
// a 0 b 1 c 2 d 3
  • notice forEach The second parameter in is thisArg : It means pointing to the callback function this Point to
var array1 = ['a', 'b', 'c'];
var array2 = ['1','2','3'];
array1.forEach(function(currentValue, index, arr) {
    
    console.log(currentValue, index, arr, this);
},array2);

#  Output 
//  If  forEach()  Pass the  thisArg  Parameters , When called , It will be passed on to  callback  function , As it is  this  value . otherwise , Will be introduced into  undefined  As it is  this  value 
> "a" 0 ["a", "b", "c"] ["1", "2", "3"] 
> "b" 1 ["a", "b", "c"] ["1", "2", "3"]
> "c" 2 ["a", "b", "c"] ["1", "2", "3"]

  • The final code

const list = ['a', 'b', 'c', 'd'];
const list2 = [1, 2, 3];
//  Be careful not to use  => (fn) {...}  How to write it , because this The object will not be found 
// item:  Return the value of each array 
// index:  Return the index corresponding to the array  0 1 2....
// array:  Return the array itself of the loop 
Array.prototype.newForEach = function (
  fn: (item: any, index: number, array: any[]) => void,
  thisArg?: any,
) {
    
  console.log(this); //  there this Will point to  list - ['a', 'b', 'c', 'd']
  const len = this.length;
  for (let i = 0; i < len; i++) {
    
    //  Pass the element to the callback function 
    if (thisArg) {
    
      fn.call(thisArg, this[i], i, this);
    } else {
    
      fn(this[i], i, this);
    }
  }
};
list.newForEach(function (currentValue, index, arr) {
    
  console.log(currentValue, index, arr, this);
}, list2);

 Insert picture description here

原网站

版权声明
本文为[Sam young]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130610294685.html