const selectedOption = { value: null , ...other }
if (selectedOption && selectedOption.value ) {
console.log('it is?')
}
我认为控制台一定不会出现
但它是为什么发生的呢?
selectedOption.value 为 null,所以它是假值,不是吗?
<小时/>抱歉,我犯了一个错误
最佳答案
是的,null
是一个虚假值。虚假值为 null
、undefined
、0
、""
、NaN
、当然,假
。所有其他值都是真实的。
但是,如 Mark指出in a comment ,这并不一定意味着您不会进入if
的正文,因为selectedOption.value
可能不是null
(例如,如果 other
有一个非 null
value
):
const other = {value: 42};
const selectedOption = { value: null , ...other }
if (selectedOption && selectedOption.value ) {
console.log('it is?')
}
selectedOption.value
如果点差采用不同的顺序,将肯定为null
:
const other = {value: 42};
const selectedOption = { ...other, value: null }
if (selectedOption && selectedOption.value ) {
console.log('it is?');
} else {
console.log("definitely false");
}
对象初始值设定项按源代码顺序进行处理,因此后面的属性优于较早的同名属性。
关于javascript - 令人困惑的逻辑运算 if(null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205721/