【问题标题】:How to write this in shorthand javascript如何用简写的javascript写这个
【发布时间】:2017-06-16 09:34:45
【问题描述】:

我知道如何用简写的 javascript if else 语句写一行。 我不知道如何写两个。我的语法不断出错。 这就是我要转换为速记的内容。

if (node === newValue) {
  console.log('did find case') 
  return true
} else {
  console.log('didn\'t find case') 
}

我正在尝试将上面的代码转换成这个,但我收到一个错误

  node === newValue
    ? console.log('did find case') 
      true
    : console.log('didn\'t find case') 

【问题讨论】:

  • 为什么要在可读的情况下缩短代码?
  • 我同意@Tushar 的观点,那就是让您的代码可读。如果您担心文件大小,请考虑使用 js 缩小服务,例如 UglifyJS
  • 由于console.log用于调试,我将代码更改为return (node === newValue);代码结构不应更改以支持调试。
  • @user2182349:在OP的代码中,else情况下没有返回。
  • @Amadan - 也没有函数语句,可能有更多代码,函数完全有可能在 if 语句之后终止。

标签: javascript conditional-operator shorthand


【解决方案1】:

?: 和 if 不等价,尤其不应将?: 视为“简写if”。 if 作用于语句和语句块; ?: 处理表达式。虽然所有表达式都是语句,并且许多语句也是表达式,但 return 不是表达式:无法在 ?: 中使用它。

【讨论】:

  • 谢谢。这更有意义。我将不得不回去审查基本面
猜你喜欢
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
  • 2013-09-20
相关资源
最近更新 更多