Fe-interview: [js] 第251天 举例说明什么是短路求值?

Created on 22 Dec 2019  ·  1Comment  ·  Source: haizlin/fe-interview

第251天 举例说明什么是短路求值?

我也要出题

js

Most helpful comment

短路求值即利用 ||(逻辑或) 和 &&(逻辑与)的短路特性进行赋值:

const number = test || 0;

test值为truthy时,取test的值,否则取0。这样可以避免number被赋为NaNnullundefinedfalse等值。


const number = test && test.value;

test值为truthy时,再去取test.value并返回其值,否则返回false。这样可以避免test为空时,test.value报空指针异常。

>All comments

短路求值即利用 ||(逻辑或) 和 &&(逻辑与)的短路特性进行赋值:

const number = test || 0;

test值为truthy时,取test的值,否则取0。这样可以避免number被赋为NaNnullundefinedfalse等值。


const number = test && test.value;

test值为truthy时,再去取test.value并返回其值,否则返回false。这样可以避免test为空时,test.value报空指针异常。

Was this page helpful?
0 / 5 - 0 ratings