Not*_*bad 3 javascript syntax logical-operators
var array = props && props.children.find(ele => ele && ele.length);
Run Code Online (Sandbox Code Playgroud)
弄乱我的是AND(&&).前一行代码不应该返回一个布尔值吗?我知道它没有,因为我已经尝试过它,它返回一个数组.
谁能解释一下这里发生了什么?
您发布的示例使用了JavaScript语言的一些功能:
&&和||运营商的短路性质:https://en.wikipedia.org/wiki/Short-circuit_evaluation&&与||运营商返回"计算值",而不是一个boolean值:为什么不逻辑运算符(&&和||)总是返回一个布尔结果?它在语义上等同于:
var array = undefined;
if( props /* is not null or undefined or empty-string */ ) {
array = props.children.find( ele => ele && ele.length );
}
Run Code Online (Sandbox Code Playgroud)
(注意谓词中的附加&&内容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;
} );
}
Run Code Online (Sandbox Code Playgroud)
它也可以与C#中的"Elvis operator"又名安全导航操作员进行比较:
var array = props?.children.find( e => e?.length );
Run Code Online (Sandbox Code Playgroud)
该&&运营商首先计算其左操作数,在这种情况下,只是props-如果不是falsy(不为空,未定义或空字符串),那么它的计算结果正确的操作数(在这种情况下,props.children.find函数调用).请注意,空数组不是假的.
如果props是假的,则.children.find不会进行调用,从而防止运行时错误.