[英]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.