如何用速记javascript写这个

时间:2017-01-31 03:39:34

标签: javascript conditional-operator shorthand

我知道如何用简写的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') 

1 个答案:

答案 0 :(得分:2)

?:if不等同,特别是我们不应该将?:视为"简写if" 。 if适用于语句和语句块; ?:适用于表达式。虽然所有表达式都是语句,而且许多语句也是表达式,但return不是表达式:在?:中无法使用它。