簡體   English   中英

從頭開始實現reduce(),不確定JS如何知道什么是“數組”

[英]Implementing reduce() from scratch, not sure how JS knows what “array” is

我正在嘗試從頭開始實現reduce()。 我能夠使它工作,但是即使我從未在任何地方定義它,javascript怎么知道“數組”是什么?

function reduce(callback, initialVal) {
  var accumulator = (initialVal === undefined) ? undefined : initialVal;
  for (var i=0; i<array.length; i++) {
    if (accumulator !== undefined) {
      accumulator = callback(accumulator, array[i], i, array);
    } else {
      accumulator = array[i]
    }
  }
  return accumulator;
};

// testing a basic sum
arr = [1,2,3]
arr.reduce( (accumulator, elem) => accumulator+=elem )

編輯:我得到了它的工作:DI因為我正在Array.prototype下創建一個新方法,所以將'array'更改為“ this”。

Array.prototype.myReduce = function(callback, initialVal) {
  var accumulator = (initialVal !== undefined) ? initialVal : undefined;
  for (var i=0; i<this.length; i++) {
    if (accumulator !== undefined) {
      accumulator = callback(accumulator, this[i], i, this);
    } else {
      accumulator = this[i]
    }
  }
  return accumulator;
};

arr.myReduce( (accumulator, elem) => accumulator+=elem )
arr.myReduce( (accumulator, elem) => accumulator+=elem , 100)

你很親密 似乎缺少的一種見解是,在函數內部, this將定義為調用函數的數組。 所以,你可以使用this在您目前使用的地方array ,這在你的函數是不確定的(如您懷疑)。 您可能還希望根據是否傳入初始值在其他位置啟動循環。例如:

 function reduce(callback, initialVal) { var accumulator = ( initialVal === undefined) ? this[0] : initialVal; var start = (initialVal === undefined) ? 1 : 0 for (var i = start; i < this.length; i++) { accumulator = callback(accumulator, this[i]) } return accumulator; }; Array.prototype.myReduce = reduce // no init value console.log([1, 2, 3].myReduce((sum, curr) => sum + curr)) // init value: console.log([1, 2, 3].myReduce((sum, curr) => sum + curr, 1000)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM