JavaScrip條件求值

// 當數組長度不爲空時,
// 不良寫法:
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編程精粹》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章