1 回答

TA貢獻1841條經驗 獲得超3個贊
您是對的,if 和 else 條件僅在“非此即彼”的基礎上執行。if 和 else 條件不能在同一次迭代或一次函數調用中執行。
然而,在您共享的代碼中,有一個 for 循環正在迭代“words”數組,這可能是您感到困惑的原因。
for 循環本質上會調用循環內的任何內容 n 次,直到不滿足結束條件。在這種情況下,只要words數組在當前元素之后還有更多元素即可。
因此,如果您的單詞數組有 2 個單詞,則 for 循環將調用內部 if 和 else 語句塊 2 次:
第一次,因為 'i' 的值為 0,小于words.length(words.length 為 2,因此words.length-1 為 1),因此將調用您的 else 條件。
第二次,因為i的值等于words array的長度- 1(即1),所以if條件滿足,if將被執行。
words = ['Hello', 'world']
var sentence = '';
for (var i = 0; i < words.length; i++) {
if (i === words.length - 1) {
console.log('if condition: ', words[i]);
sentence += words[i] + '.';
} else {
console.log('else condition: ', words[i]);
sentence += words[i] + ' ';
}
}
console.log(sentence);
上面的代碼與下面的代碼的工作方式相同:
words = ['Hello', 'world']
function ifElseBlock() {
if (i === words.length - 1) {
console.log('if condition: ', words[i]);
sentence += words[i] + '.';
} else {
console.log('else condition: ', words[i]);
sentence += words[i] + ' ';
}
}
var sentence = '';
for (var i = 0; i < words.length; i++) {
ifElseBlock();
}
console.log(sentence);
正如我們所看到的,在這兩種情況下,for 循環都會執行兩次,因為words 數組有 2 個元素。
我相信下面的代碼會進一步澄清它:
const words = ['hello', 'world']
let sentence = '';
if (0 === words.length - 1) {
sentence += words[1] + '.';
} else {
sentence += words[0] + ' ';
}
console.log(sentence)
這次只執行 else 條件,因為我沒有使用循環來迭代words數組,而是在if條件中硬編碼了0,并將其與words.length-1進行比較,這將是1,因為words數組的長度是2.
添加回答
舉報