Javascript 无法理解for循环
有人能给我解释一下下面代码的for循环吗 我无法理解for循环中内容的含义 变量颜色=[红色、黄色、蓝色]; var text=; var i; 对于i=0;i.长度;i++{ 文本+=颜色[i]+; } document.getElementByIdColorList.innerHTML=文本;Javascript 无法理解for循环,javascript,arrays,loops,Javascript,Arrays,Loops,有人能给我解释一下下面代码的for循环吗 我无法理解for循环中内容的含义 变量颜色=[红色、黄色、蓝色]; var text=; var i; 对于i=0;i.长度;i++{ 文本+=颜色[i]+; } document.getElementByIdColorList.innerHTML=文本; 看看我添加的评论: var colours = ["Red", "Yellow", "Blue"]; // Define an array
看看我添加的评论:
var colours = ["Red", "Yellow", "Blue"]; // Define an array with all the color names
var text = ""; // Initialize "text" as empty string
var i; // Declare the loop variable
// For loop, start with 0(i=0), end with the length of array "colours"(i < colours.length), increase i by one after each loop iteration (i++)
for (i = 0; i < colours.length; i++) { // For each color in array colors...
text += colours[i] + " "; // Add the name of the current color to "text", followed by a whitespace
}
// "text" now contains all colors sepearted by whirespaces
document.getElementById("colourList").innerHTML = text; // Show all the colors in the "colourList" HTML element
循环用于迭代数组颜色,以按空格连接所有值,即红色、黄色、蓝色
const colours = ["Red", "Yellow", "Blue"];
let text = "";
let i;
for (i = 0; i < colours.length; i++) {
text += colours[i] + " ";
}
document.getElementById("colourList").innerHTML = text;
此外,我还自由地将var更改为let和const。请尽可能使用let和const代替var 只是使用for循环从颜色中一个接一个地获取颜色,并将其附加到文本中。您具体不明白什么?+=运算符?+操作员?为数组建立索引?for循环的作用是什么?您是否期望代码的结果与您观察到的结果不同?简而言之,循环正在执行text=colors[0]++colors[1]++colors[2]+;OP要求理解for循环是如何工作的,而不是让他们的代码受到批评和重写。这是如何回答这个问题的?
1. text += colours[0] + " "; // text = "Red "
2. text += colours[1] + " "; // text = "Red Yellow "
3. text += colours[2] + " "; // text = "Red Yellow Blue "