【问题标题】:How avoid error - function-name(...) is not a function in quiz?如何避免错误 - function-name(...) 不是测验中的函数?
【发布时间】:2020-06-21 15:21:45
【问题描述】:

我想通过 codewars -https://www.codewars.com/kata/53cf7e37e9876c35a60002c9/train/javascript 的测验,但我无法避免通过错误:“TypeError: add(...) is not a function”

function curryPartial(){
  let args= [...arguments]
  let fn = args[0]
  console.log(fn.length)
  function cur(){
    let argsCur= [...arguments]
    return curryPartial(...args,...argsCur)
  }
  cur.valueOf = ()=>{
    //return args.reduce((a,b)=>a+b)
    // console.log(...args)
    // const res = +fn(...args.slice(1))
    // return res
  }
  return cur

}
function add(a, b, c) {
  return a + b + c;
}
console.log(+curryPartial(add(1,2)(3)))

如何避免此错误以通过测验?

【问题讨论】:

  • 您想在add(1,2)(3) 中做什么?正如现在所写的那样,解析器期望add(1, 2) 返回一个函数,因此您可以使用参数3 调用它。但它返回一个数字。由于 add 函数需要 3 个参数,我假设您希望 3 成为 add 函数的第三个参数。如果是这样,您必须将其写为add(1, 2, 3)
  • All these examples should produce the same result: curryPartial(add)(1)(2)(3); //6 curryPartial(add, 1)(2)(3); //6 curryPartial(add, 1)(2, 3); //6
  • curryPartial()本身返回一个函数,所以可以调用返回值。但add 函数只返回一个数字。您希望如何将其作为函数调用?

标签: javascript function


【解决方案1】:

关于add(1,2)(3)

当然会出现错误,add 函数会返回一个值,通过执行add(1,2)(3),您正在执行add(1,2) 的返回值并传递一个3,这不是一个函数,所以错误有长大了。

执行语句应该是

console.log(+curryPartial(add)(1,2)(3))
// not
console.log(+curryPartial(add(1,2)(3)))

注意括号对

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 2017-04-07
    • 1970-01-01
    • 2014-01-26
    • 2020-08-19
    • 2018-07-29
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多