[JS] Loop through an array of strings with a while loop and print them


#1

Hi Everyone,

I am trying to loop through a simple array of string such as:

var names = ["AB", "CB", "EF"];

and then print them with a while loop on 3 different lines.

With a for loop, no problem so far:

for (var i = 0; i < names.length; i++) {
console.log("With a FOR, the names are:" + " " + names[i]);
}

And with my current while loop, no problem either:

while (names.length <= 3) {
console.log("With a WHILE, the names are:" + " " + names);
names.length++;
};

Nevertheless, I can't figure out how to print 3 different lines on the console with "With a WHILE, the names are: ...".

Any thoughts on this?

Much appreciated!
Thanks,


#2

well, you still need numbers to serve as index values.

so here is what i would do:

var i = 0;
while (i < names.length){
   console.log(names[i])
   i++;
}

.length will give you the length of the list, i would never increase the length like that

i would simply use a counter (just like you did with for) and check if this is less then the amount of names in the array


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.