简体   繁体   English

为什么我的JavaScript OR语句未返回正确的值?

[英]Why does my JavaScript OR statement not return the correct value?

I'm stuck with the following: 我坚持以下几点:

foo = properties[field] || overrides.default || config.widget.default || undefined;

with

console.log(properties[field])     // undefined
console.log(overrides.default)     // 0
console.log(config.widget.default) // undefined

So as I understand, foo should be 0 . 因此,据我了解, foo应该为0 Yet... it's undefined 但是... undefined

This still works: 这仍然有效:

foo = properties[field] || overrides.default;

But as soon as I add another OR option, it does not work anymore. 但是,一旦我添加了另一个OR选项,它便不再起作用。

Question : 问题
Why is my 2nd operand with value=0 not overriding the undefined operands? 为什么我的value=0第二个操作数不覆盖undefined操作数?

Thanks! 谢谢!

The || || operator returns its left-hand operand if it is truthy, otherwise it returns the right-hand operand. 如果为真,则运算符将返回其左侧操作数,否则返回右侧操作数。

In your example, all operands have falsey values, so the compound || 在您的示例中,所有操作数都具有假值,因此复合|| statement returns the right-most value. 语句返回最右边的值。

In JS, the following are all falsey: 0 , "" (empty string), undefined , null , NaN . 在JS中,以下所有内容均为false: 0"" (空字符串), undefinednullNaN And of course false . 当然是false All other values are truthy (including strings like "0" or "false" because they're not empty strings). 所有其他值都是真实的(包括字符串"0""false"因为它们不是空字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM