Start the "count" of an array with 1 and not with 0

6

The fact is that I have the script done, which executes a loop to generate a series of sentences. I want the array account to start with 0 and not 1 , so that it makes sense.

var colours = ["White", "Red", "Black", "Purple", "Grey", "Yellow", "Blue"];
var cities = ["Japan", "Korea", "Spain", "England", "China", "Singapur", 
"Rumania"];
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", 
"Saturday", "Sunday"];

for (var n = 0; n < colours.length; n++) {
    document.write("My " + n + " choice is " + colours[n] + " in " + 
cities[n] + " on " + days[n] + "<br>");
}

This is the result I currently get.

It's probably easy but I can not see it. Thanks for the help in advance.

    
asked by Kelvin Macay 08.01.2018 в 19:20
source

2 answers

7

One option is simply to add 1 to the value of n only to print the value from 1 to n:

var colours = ["White", "Red", "Black", "Purple", "Grey", "Yellow", "Blue"];
var cities = ["Japan", "Korea", "Spain", "England", "China", "Singapur", 
"Rumania"];
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", 
"Saturday", "Sunday"];

for (var n = 0; n < colours.length; n++) {
    document.write("My " + (n + 1) + " choice is " + colours[n] + " in " + 
cities[n] + " on " + days[n] + "<br>");
}

or add a variable that works as a counter that starts from 1:

var colours = ["White", "Red", "Black", "Purple", "Grey", "Yellow", "Blue"];
var cities = ["Japan", "Korea", "Spain", "England", "China", "Singapur", 
"Rumania"];
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", 
"Saturday", "Sunday"];
var counter = 1;
for (var n = 0; n < colours.length; n++) {
    document.write("My " + counter + " choice is " + colours[n] + " in " + 
cities[n] + " on " + days[n] + "<br>");
 counter++;
}
    
answered by 08.01.2018 / 19:24
source
2

Mmm if you only want to appear in the account, you can use:

 document.write("My " + (n+1) + " choice is " + colours[n] + " in " + cities[n] + " on " + days[n] + "<br>");

since if you only put it there it will not affect the positions of your array and the increased account will appear after "My". I hope you serve

    
answered by 08.01.2018 в 19:23