简体   繁体   中英

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

I'm trying to implement reduce() from scratch. I was able to get it working, but how does javascript know what "array" is even though I never defined it anywhere?

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 )

EDIT: I got it working :DI Changed 'array' to "this" since I was creating a new method under Array.prototype.

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)

You are pretty close. The one insight that seems to be missing is that inside your function, this will be defined as the array your function was called on. So you can use this in the places you're currently using array , which in your function will be undefined (as you suspected). You probably also want to start the loop in a different place depending on whether the initial value was passed in. For example:

 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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM