条件运算符“?:”可以被视为 JavaScript 中 if-else 语句的替代吗?
Can conditional operator " ? : " be considered as an alternative to if-else statement in JavaScript?
有人在研讨会上问我这个问题,以及 JavaScript 中 if-else
语句的替代方案,但 switch
除外。条件运算符只是 if-else
的 shorthand 吗?
JS 是一种 "phrasal" 编程语言,严格区分 表达式 (值和运算符)和 语句 。 ?
是一个运算符,可以在表达式中使用:
a = x ? y : z
而 if
不能,因为它是一个语句:
a = if (x) ... // syntax error
另一方面,当在适当的上下文中使用时,每个表达式也是一个语句:
while (1)
a = x ? y : z;
所以可以公平地说 ?
比 if
更 "broader" 因为它可以在两种情况下使用。这当然并不意味着它应该(而不是)。
如果您对表达条件逻辑的其他方式感兴趣,可以使用布尔运算符:
a && do_something() // "if a do_something()"
b || do_something() // "if not b do_something()"
虽然这样的用途大多被认为是糟糕的风格。
有点shorthand,但仅在return从两个可能的表达式.
ing/获取值或对象的情况下]
示例:
// inside a function
if (condition) { return X; } else { return Y; }
// Functionally equivalent to
return condition ? X : Y;
var tmp;
if (condition) { tmp = GetFoo(123); } else { tmp = GetBar(456); }
DoSomething(tmp);
// Functionally equivalent to
DoSomething(condition ? GetFoo(123) : GetBar(456));
如果没有 return 个值,仍然存在等效性,但人们可能会因为这样做而对您大喊大叫:
if (condition) { A(); } else { B(); }
// *shudder*
condition ? A() : B();
而以下是不可能或至少很难变成 ?:
:
if (condition) { A(); return true; } else { B(); return false; }
// Reason: code blocks contain multiple statements
if (condition) { tmp = GetFoo(123); }
// Reason: no "else"-block (or you need to construct/invent one)
有人在研讨会上问我这个问题,以及 JavaScript 中 if-else
语句的替代方案,但 switch
除外。条件运算符只是 if-else
的 shorthand 吗?
JS 是一种 "phrasal" 编程语言,严格区分 表达式 (值和运算符)和 语句 。 ?
是一个运算符,可以在表达式中使用:
a = x ? y : z
而 if
不能,因为它是一个语句:
a = if (x) ... // syntax error
另一方面,当在适当的上下文中使用时,每个表达式也是一个语句:
while (1)
a = x ? y : z;
所以可以公平地说 ?
比 if
更 "broader" 因为它可以在两种情况下使用。这当然并不意味着它应该(而不是)。
如果您对表达条件逻辑的其他方式感兴趣,可以使用布尔运算符:
a && do_something() // "if a do_something()"
b || do_something() // "if not b do_something()"
虽然这样的用途大多被认为是糟糕的风格。
有点shorthand,但仅在return从两个可能的表达式.
ing/获取值或对象的情况下]示例:
// inside a function
if (condition) { return X; } else { return Y; }
// Functionally equivalent to
return condition ? X : Y;
var tmp;
if (condition) { tmp = GetFoo(123); } else { tmp = GetBar(456); }
DoSomething(tmp);
// Functionally equivalent to
DoSomething(condition ? GetFoo(123) : GetBar(456));
如果没有 return 个值,仍然存在等效性,但人们可能会因为这样做而对您大喊大叫:
if (condition) { A(); } else { B(); }
// *shudder*
condition ? A() : B();
而以下是不可能或至少很难变成 ?:
:
if (condition) { A(); return true; } else { B(); return false; }
// Reason: code blocks contain multiple statements
if (condition) { tmp = GetFoo(123); }
// Reason: no "else"-block (or you need to construct/invent one)