首页 > 技术文章 > JavaScrip条件求值

jeff-ideas 2018-10-15 17:56 原文

// 当数组长度不为空时,
// 不良写法:
if ( array.length > 0 ) ...
// 测试逻辑真(优良的写法):
if ( array.length ) ...
// 当数组长度为空时,
// 不良写法:
if ( array.length === 0 ) ...
// 测试逻辑真(优良的写法):
if ( !array.length ) ...
// 检查字符串是否为空时,
// 不良写法:
if ( string !== "" ) ...
// 测试逻辑真(优良的写法):
if ( string ) ...
// 检查字符串是否为空时,
// 不良写法:
if ( string === "" ) ...
// 测试逻辑假(优良的写法):
if ( !string ) ...
// 检查引用是否有效时,
// 不良写法:
if ( foo === true ) ...
// 优良的写法:
if ( foo ) ...
// 检查引用是否无效时,
// 不良写法:
if ( foo === false ) ...
// 优良的写法:
if ( !foo ) ...
// 这样写的话,0、""、null、undefined、NaN也能够满足条件
// 如果你必须针对false测试,可以使用:
if ( foo === false ) ...
// 引用可能会是null或undefined,但绝不会是false、""或0,
// 不良写法:
if ( foo === null || foo === undefined ) ...
// 优良的写法:
if ( foo == null ) ...
// 别把事情复杂化
return x === 0 ? 'sunday' : x === 1 ? 'Monday' : 'Tuesday';
// 这样写更好:
if (x === 0) {
return 'Sunday';
} else if (x === 1) {
return 'Monday';
} else {
return 'Tuesday';
}
// 锦上添花的写法:
switch (x) {
case 0:
return 'Sunday';
case 1:
return 'Monday';
default:
return 'Tuesday';
}

《Javascript编程精粹》

 
 

推荐阅读