【问题标题】:CoffeeScript Default ArgumentsCoffeeScript 默认参数
【发布时间】:2014-05-20 23:35:53
【问题描述】:

我正在查看来自CoffeeScript: Accelerated Development 的以下示例

x = true
showAnswer = (x = x) ->
  console.log if x then 'It works!' else 'Nope.'

console.log "showAnswer()", showAnswer()
console.log "showAnswer(true)", showAnswer(true)
console.log "showAnswer(false)", showAnswer(false)

我不明白为什么每次测试都会出现showAnswer(...) undefined

Nope.
showAnswer() undefined
It works!
showAnswer(true) undefined
Nope.
showAnswer(false) undefined

请解释每个案例的输出。

【问题讨论】:

  • 附带说明,如果你想给它一个默认值,你不需要在你的函数之前定义x = true(x = true) -> 是一个有效的(我认为是首选的)方法签名。

标签: coffeescript


【解决方案1】:

不要忘记,默认情况下,CoffeeScript 返回函数中的最后一条语句。所以你的showAnswer 函数实际上说的是:

showAnswer = (x = x) ->
    return console.log if x then 'It works!' else 'Nope.'

或编译成 JavaScript:

showAnswer = function(x) {
  if (x == null) {
    x = x;
  }
  return console.log(x ? 'It works!' : 'Nope.');
};

要意识到的另一件事是console.log 方法返回undefined。因此,当您记录 showAnswer 方法的结果时,它将打印 undefined

如果我正确理解你的意图,我会修改你原来的功能来做到这一点:

showAnswer = (x = x) ->
  if x then 'It works!' else 'Nope.'

或者,修改您的 console.log 语句:

console.log "showAnswer()"
showAnswer()

console.log "showAnswer(true)"
showAnswer(true)

console.log "showAnswer(false)"
showAnswer(false)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2010-12-01
    • 2011-08-23
    相关资源
    最近更新 更多