Skip to content

实现 Array.prototype.reduce 方法 #13

Open

Description

@CodeRookie262

根据 Array.prototype.reduce 的特性进行封装

Link:特性

Activity

  1. CodeRookie262 commented on Jan 4, 2021

    @CodeRookie262
    OwnerAuthor
    /**
     *
     * @param {Function} callback
     *  callback 可接收4个参数
     * - accumulator - 累计器累计回调的返回值;
     * - currentValue - 数组中正在处理的元素;
     * - index? - 数组中正在处理的当前元素的索引;
     * - array? - 源数组;
     *
     * @param {any} [initialValue]
     *  作为第一次调用 callback函数时的第一个参数的值。
     *  如果没有提供初始值,则将使用数组中的第一个元素。
     *  在没有初始值的空数组上调用 reduce 将报错。
     */
    function customReduce(callback, initialValue) {
      let context = this; //获取数组
      if (context.length === 0) throw new Error('TypeError: 数组长度不能为 0');
      let hasInit = typeof initialValue === 'undefined'; //判断是否有初始值
    
      for (var i = hasInit ? 1 : 0; i < context.length; i++) {
        initialValue = callback(
          hasInit ? context[i] : initialValue,
          context[i],
          i,
          context
        );
      }
    
      return initialValue;
    }
    
    Array.prototype.customReduce = customReduce;
  2. jiawood commented on Mar 30, 2022

    @jiawood

    customReduce实现有点小问题哈

    function customReduce(callback, initialValue) {
      let context = this; //获取数组
      if (context.length === 0) throw new Error('TypeError: 数组长度不能为 0');
      let hasInit = typeof initialValue === 'undefined'; //判断是否有初始值
    
      for (var i = hasInit ? 1 : 0; i < context.length; i++) {
        initialValue = callback(
          hasInit ? context[0] : initialValue,
          context[i],
          i,
          context
        );
        hasInit = false  
      }
    
      return initialValue;
    }
    
    Array.prototype.customReduce = customReduce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions