Skip to content

编程题:实现一个add方法 #16

Open

Description

@CodeRookie262

例如

function add(){//...}

add(1)(2,3)(4).value()   
输出: 10

Activity

  1. CodeRookie262 commented on Jan 7, 2021

    @CodeRookie262
    OwnerAuthor

    可以利用闭包的机制保存一个变量,add 执行时对这个私有变量做操作,当调用 value() 时返回结果即可。

    const add = (function () {
      let result = 0;
      function add(...nums) {
        result += nums.reduce((a, b) => a + b);
        return add;
      }
    
      add.value = function () {
        return result;
      };
    
      return add;
    })();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions