为什么我的 for 循环卡在第二个选项上?

第一个项目 - 需要从嵌套数组中提取以进行测验,但循环以某种方式卡在数组中的第二个位置并跳过第一个。也陷入了无限循环——


var quiz = [ 

             [ "what color is the sky?" , "blue" ],

             [ "what color are most apples?", "red" ],

             [ "what color is coffee?" , "black" ]

];


var i;

for ( i = 0; i < 3; i++) {

  if (i = 0) { 

    var ans1 = prompt(quiz[0][0]);

  } else if (i = 1) {

    var ans2 = prompt(quiz[1][0]);

  } else {

    var ans3 = prompt(quiz[2][0]);

  }

}



document.write(ans1 + ans2 + ans3);

我的逻辑是,如果 i = 0 从一开始它应该运行第一个提示,然后完成循环将 1 添加到 i 变量,然后运行第二个提示等。


我尝试查找它,尝试了一个while循环,尝试将最后一个else更改为else if (i = 2)。


紫衣仙女
浏览 164回答 3
3回答

呼啦一阵风

您需要更改if (i = 0)为if (i == 0).&nbsp;在 Javascript 和许多其他编程语言中,=意味着赋值,但==意味着比较。由于您尝试与i整数进行比较,因此您需要比较运算符,而不是赋值运算符。

侃侃无极

问题在于=操作符使用==操作符或更好===,但同样在这种情况下您不需要循环或条件。var quiz = [&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[ "what color is the sky?" , "blue" ],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[ "what color are most apples?", "red" ],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[ "what color is coffee?" , "black" ]];var ans1 = prompt(quiz[0][0]);var ans2 = prompt(quiz[1][0]);var ans3 = prompt(quiz[2][0]);document.write(ans1 + ans2 + ans3);

12345678_0001

一个人=是一个任务。你想要一个双重方程来做比较:var quiz = [&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[ "what color is the sky?" , "blue" ],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[ "what color are most apples?", "red" ],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[ "what color is coffee?" , "black" ]];var i;for ( i = 0; i < 3; i++) {&nbsp; if (i == 0) {&nbsp;&nbsp; &nbsp; var ans1 = prompt(quiz[0][0]);&nbsp; } else if (i == 1) {&nbsp; &nbsp; var ans2 = prompt(quiz[1][0]);&nbsp; } else {&nbsp; &nbsp; var ans3 = prompt(quiz[2][0]);&nbsp; }}document.write(ans1 + ans2 + ans3);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript