var array = props && props.children.find(ele => ele && ele.length);
让我感到困惑的是 AND (&&
)。上一行代码不应该返回一个 bool 值吗?我知道它不会,因为我已经尝试过了,它返回一个数组。
谁能解释一下这里发生了什么?
最佳答案
您发布的示例使用了 JavaScript 语言的一些功能:
- “虚假”-ness:https://developer.mozilla.org/en-US/docs/Glossary/Falsy
&&
和||
运算符的短路特性:https://en.wikipedia.org/wiki/Short-circuit_evaluation&&
和||
运算符返回“计算值”而不是boolean
值:Why don't logical operators (&& and ||) always return a boolean result?
它在语义上等同于:
var array = undefined;
if( props /* is not null or undefined or empty-string */ ) {
array = props.children.find( ele => ele && ele.length );
}
(注意 find
谓词中的附加 &&
,所以完整的变成这样):
var array = undefined;
if( props /* is not null or undefined or empty-string */ ) {
array = props.children.find( function( ele ) {
if( ele /* is not null or undefined or empty-string */ ) {
return ele.length;
}
return undefined;
} );
}
它也可以与 C# 中的“猫王运算符”又名安全导航运算符进行比较:
var array = props?.children.find( e => e?.length );
说明:
&&
运算符首先计算它的左操作数,在本例中只是 props
- 如果它不是假的(不是 null、undefined 或空字符串)然后它计算正确的操作数(在本例中为 props.children.find
函数调用)。请注意,空数组不是假的。
如果 props
为假,则不会进行 .children.find
调用,从而防止运行时错误。
关于javascript - 为什么 AND (&&) 运算符返回数组而不是 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723873/