简体   繁体   中英

Not able to understand the for loop

Can anyone please explain the for loop of the following code to me?

I am not able to understand the meaning of the content in the for loop.

 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>

Have a look at the comments i added:

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

The loop is used to iterate over the array colors to concatenate all the value ie Red, yellow, blue by space.

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

Iterations:

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

Also I took the liberty to change var to let and const. Plese use let and const insteadof var wherever possible. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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