【问题标题】:Short circuit evaluation with ternary output [closed]三元输出的短路评估[关闭]
【发布时间】:2018-12-19 16:19:25
【问题描述】:

我正在使用短路评估来分配一些变量。我不得不在其中一些中使用三元运算符,但它的行为不像我预期的那样:

console.log(false || "bar"); // Outputs "bar"
console.log("foo" || "bar"); // Outputs "foo"
console.log("foo" || (true) ? "42" : "bar"); // Ouputs "42", why ?

第三个console.log不应该输出“foo”吗?

【问题讨论】:

标签: javascript


【解决方案1】:
console.log("foo" || (true) ? "42" : "bar"); // Ouputs "42", why ?

因为它被评估为

console.log(("foo" || true) ? "42" : "bar");

("foo" || true) 首先被评估为真实值。

也许你的意思是你的括号放错了地方

console.log("foo" || (true ? "42" : "bar"));

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 1970-01-01
    • 2021-10-10
    • 2015-11-14
    • 2017-01-21
    • 2012-02-10
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多