代码之家  ›  专栏  ›  技术社区  ›  Guy

reduce方法在没有给出初始值的情况下将累加器设置为数组的第一项

  •  1
  • Guy  · 技术社区  · 6 年前

    marked as optional ,如果不提供它,则减速机将使用输入数组的第一项初始化累加器。为什么?

    const output = Object.keys({
      name: "david",
      age: 30
    }).reduce((memo, key) => {
      return [...memo, key];
    })
    
    console.log(output);
    
    // output: ["n", "a", "m", "e", "age"]
    

    const output = Object.keys({
      name: "david",
      age: 30
    }).reduce((memo, key) => {
      return [...memo, key];
    }, [])
    
    console.log(output);
    
    // output: ["name", "age"]
    

    2 回复  |  直到 6 年前
        1
  •  2
  •   Artyer    6 年前

    reduce 可以递归定义,例如:

    // <Except some details to do with empty slots>
    Array.prototype.reduce = function(f, initial_value) {
        if (this.length === 0) {
            if (arguments.length > 1) {
                return initial_value;
            }
            throw TypeError('reduce of empty array with no initial value');
        }
        if (arguments.length > 1) {
            // Starting value given.
            const copy = this.slice();
            const first = copy.shift();
            return copy.reduce(f, f(initial_value, first));
        } else {
            // No starting value given
            // What should happen here?
            const copy = this.slice();
            const first = copy.shift();
            // return copy.reduce(f, f(intial_value, first));
    
            // Nothing was given as the initial_value.
            // What is the same as "nothing"?
            // Applying the function with an `identity` value
            // so that `f(identity, first) === first` means
            // that this `identity` is the same as nothing.
    
            // Of course, we can't know what that is if there
            // are no elements in the list, so we threw an error before.
            return copy.reduce(f, first);
        }
    };
    

    一般来说 减少 (a, b) => a + b ,那将是 0 . 为了 (a, b) => a * b ,可能是 1 . 为了 (a, b) => Math.max(a, b) ,可能是 -Infinity

    对于你的功能,正如你正确地写的, [] .

    一般来说,初始值应该是 identity . 所以如果你不违约, 减少

    在您的例子中,它稍微复杂一点,因为如果您定义“equality”,那么函数只有一个“identity” (Input) x === (Output) [x] .

    the reduce function 更多信息。

        2
  •  1
  •   KooiInc    6 年前

    扩散算子( ...memo )将第一个值转换为字符数组。从 MDN

    从索引1开始的回调函数,跳过第一个索引。如果 提供了initialValue,它将从索引0开始。

    const output = Object.keys({
      name: "david",
      age: 30,
      shoesize: 45
    }).reduce((memo, key, i) => (i < 2 ? [memo] : memo).concat(key));
    //                           ^ so convert the first value to array
    console.log(output);