繁体   English   中英

无法理解 for 循环

[英]Not able to understand the for loop

任何人都可以向我解释以下代码的for循环吗?

我无法理解 for 循环中内容的含义。

 var colours = ["Red", "Yellow", "Blue"]; var text = ""; var i; for (i = 0; i < colours.length; i++) { text += colours[i] + " "; } document.getElementById("colourList").innerHTML = text;
 <p id="colourList"></p>

看看我添加的评论:

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

该循环用于遍历数组colors以通过空格连接所有值,即红色、黄色、蓝色。

const colours = ["Red", "Yellow", "Blue"];
let text = "";
let i;
for (i = 0; i < colours.length; i++) {
  text += colours[i] + " ";
}
document.getElementById("colourList").innerHTML = text;

迭代:

1. text += colours[0] + " "; // text = "Red "
2. text += colours[1] + " "; // text = "Red Yellow "
3. text += colours[2] + " "; // text = "Red Yellow Blue "

我还冒昧地将 var 更改为 let 和 const。 请尽可能使用 let 和 const 而不是 var。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM