Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

编写一个add()函数,支持对多个参数求和以及多次调用求和 #33

Open
yizihan opened this issue Jun 19, 2020 · 0 comments

Comments

@yizihan
Copy link
Owner

yizihan commented Jun 19, 2020

编写一个add()函数,支持对多个参数求和以及多次调用求和

add(1) // 1
add(1)(2) // 3
add(1, 2)(3, 4, 5)(6) // 21
function add(...args) {
  let arr = args
  // fn() 主要是拼接参数并返回自身
  function fn(...newArgs) {
    arr = [...args, ...newArgs]
    return fn
  }
  // toString()函数会在打印函数的时候调用
  // valueOf()函数会在获取函数原始值时调用(赋值)
  fn.toString = fn.valueOf = function () {
    return arr.reduce((acc, cur) => acc + parseInt(cur))
  }
  // 返回函数,保证连续调用
  return fn
}
var num1 = add(1)(2)
// 调用fn.toString()
console.log(num1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant