初学者 javascript - “if”和“else”条件都被执行?

我是 JavaScript 初学者。据我了解,如果if不满足条件,else则执行条件;但是,在我的代码中,我看到这两个条件都被执行,因为末尾有一个点并且单词之间有空格。实际上正在执行哪个条件?


var result1 = createSentence(['I', 'am', 'worth', 'it']);

console.log('should log "I am worth it.":', result1);


function createSentence(words) {

  var sentence = "";

  for (var i = 0; i < words.length; i++) {

    if (i === words.length - 1){

        sentence += words[i] + '.';

}   else {

        sentence += words[i] + ' '

         }

}

  return sentence

}


12345678_0001
浏览 113回答 1
1回答

偶然的你

您是对的,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 = '';&nbsp; for (var i = 0; i < words.length; i++) {&nbsp; &nbsp; if (i === words.length - 1) {&nbsp; &nbsp; &nbsp; console.log('if condition: ', words[i]);&nbsp; &nbsp; &nbsp; sentence += words[i] + '.';&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; console.log('else condition: ', words[i]);&nbsp; &nbsp; &nbsp; sentence += words[i] + ' ';&nbsp; &nbsp; }&nbsp; }&nbsp;&nbsp;&nbsp; console.log(sentence);上面的代码与下面的代码的工作方式相同:&nbsp;words = ['Hello', 'world']function ifElseBlock() {&nbsp; if (i === words.length - 1) {&nbsp; &nbsp; console.log('if condition: ', words[i]);&nbsp; &nbsp; sentence += words[i] + '.';&nbsp; } else {&nbsp; &nbsp; console.log('else condition: ', words[i]);&nbsp; &nbsp; sentence += words[i] + ' ';&nbsp; }}var sentence = '';for (var i = 0; i < words.length; i++) {&nbsp; ifElseBlock();}console.log(sentence);正如我们所看到的,在这两种情况下,for 循环都会执行两次,因为words 数组有 2 个元素。我相信下面的代码会进一步澄清它:const words = ['hello', 'world']let sentence = '';&nbsp; if (0 === words.length - 1) {&nbsp; &nbsp; sentence += words[1] + '.';&nbsp; } else {&nbsp; &nbsp; sentence += words[0] + ' ';&nbsp; }console.log(sentence)这次只执行 else 条件,因为我没有使用循环来迭代words数组,而是在if条件中硬编码了0,并将其与words.length-1进行比较,这将是1,因为words数组的长度是2.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript