如何根据输入数量正确显示警报?

问题描述 投票:0回答:1

我正在参加一个非常初级的 JavaScript 课程,我们的任务是制作一个简单的循环“程序”。我决定询问用户颜色的名称,并根据他们给出的答案数量,它会显示某种结果消息。

我收到了最初的问题提示,要求输入颜色名称,但无论我做什么或尝试将警报代码放在哪里,它似乎都不起作用,有关于从这里去哪里的指导吗?尝试将警报弹出语句中的 i 更改为 colorNames 和 cName,但仍然没有任何结果

// variable for while loop
var colorNames = [];
var keepRunning = true;

// keep naming colors until done
while (keepRunning) {

    var newColor = prompt('Name as many colors as you can!' + "\n" + 'If you can\'t think of any more, leave empty and hit OK.');

    //test if prompt box has something in it or not
    if (newColor.length > 0) {
        colorNames.push(newColor);
    } else {
        keepRunning = false;
    }
}

// display color names entered 
for (var i = 0; i < colorNames.length; i++) {

    var cName = colorNames[i];
    document.write(cName + "  ");

}

//alert pop up based on number of inputs
if (keepRunning = false) {
    if (i <= 4) {
        alert('That\'s all you could think of? Refresh and try again!')
    } else if (i <= 8) {
        alert('Not bad, but you can probably do better. Refresh to play again.')
    } else if (i <= 12) {
        alert('Wow! You really know your colors! You can refresh to challenge yourself again!')
    } else if (i >= 15) {
        alert('I don\'t think anyone could do better than this, nice job!')
    }
}
javascript for-loop if-statement while-loop alert
1个回答
0
投票

你的逻辑有两个问题。

  1. if (keepRunning = false)
    条件下,
    =
    需要是
    ==
    ===
    。单个
    =
    用于分配值,而不是比较值。
  2. for
    循环之外,无法访问
    i
    。您可以通过在
    colorNames.length
    条件中使用
    if
    来修复代码,并使其更具语义。

这是经过上述修改后的工作示例:

// variable for while loop
var colorNames = [];
var keepRunning = true;

// keep naming colors until done
while (keepRunning) {
  var newColor = prompt('Name as many colors as you can!' + "\n" + 'If you can\'t think of any more, leave empty and hit OK.');

  //test if prompt box has something in it or not
  if (newColor.length > 0) {
    colorNames.push(newColor);
  } else {
    keepRunning = false;
  }
}

// display color names entered 
for (var i = 0; i < colorNames.length; i++) {
  var cName = colorNames[i];
  document.write(cName + "  ");
}

//alert pop up based on number of inputs
if (keepRunning == false) {
  if (colorNames.length <= 4) {
    alert('That\'s all you could think of? Refresh and try again!')
  } else if (colorNames.length <= 8) {
    alert('Not bad, but you can probably do better. Refresh to play again.')
  } else if (colorNames.length <= 12) {
    alert('Wow! You really know your colors! You can refresh to challenge yourself again!')
  } else if (colorNames.length >= 15) {
    alert('I don\'t think anyone could do better than this, nice job!')
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.