假設陣列中的所有元件具有從一個值不同undefined,null或者0,是
if (idx < arr.length)相當于if (arr[idx])?
uj5u.com熱心網友回復:
不。
還有其他falsy值將評估為false在if陳述句,如空字串(''):
const arrWithEmptyString = ['', '', ''];
const idx = 2;
console.log(!!(idx < arrWithEmptyString.length));
console.log(!!arrWithEmptyString[idx]);
或者,如果陣列包含一個 booleanfalse呢?
const boolArray = [true, false, true, false]
const idx = 3;
console.log(!!(idx < boolArray.length));
console.log(!!boolArray[idx]);
JS 中的型別強制/型別轉換可能會令人困惑和不可預測——在我看來,通常最好是明確地測驗你想要測驗的內容,而不是依賴弱型別比較來保存幾個字符。
uj5u.com熱心網友回復:
Alexander Nied 的回答很好,NaN 也評估為 false
const boolArray = [NaN, NaN, NaN, NaN]
const idx = 3;
console.log(!!(idx < boolArray.length));
console.log(!!boolArray[idx]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390711.html
標籤:javascript 数组 if 语句 条件语句
