Fernando Fernando - 2 months ago 7
Javascript Question

Can't use an Array with a loop JavaScript

I'm trying to create an array and later read this array like a sentence. Here is the code:

var Matriz = [english, spanish, french];
var languages = "";

for(var i = Matriz.length; i > 0; i++) {
languages = languages + ", " + Matriz[i];
}

alert(languages);


And I want to see an alert saying "english, spanish, french".

// Thank you.

Answer

Your strings require quotes, and the logic in your for loop was incorrect.

Try this

var Matriz = ['english', 'spanish', 'french'];
var languages = "";

for(var i = 0; i < Matriz.length; i++) {
    if (languages) languages = languages + ", " + Matriz[i]
    else languages = Matriz[i];
}

alert(languages);

Or something even simpler - you could just join the array and log it this way:

var Matriz = ['english', 'spanish', 'french'];
alert(Matriz.join(', '));
Comments