Stefan
Stefan

Reputation: 1059

How to use alert() to show elements of array in JS?

I wanted to try to print elements of array (animals), so that each one of its elements be in new line (\n). Unfortunately, I couldn't manage to do it. Could someone solve that problem using the logic I have made inside console.log()? And yes, I would like single alert to show given message :)

    let animals = ["fox", "elephant", "wolf"];

    console.log("List of animals:");
    for (let animal of animals) {
        let itemNum = animals.indexOf(animal) + 1;
        console.log(`${itemNum}: ${animal}`);
    }

OUTPUT:

List of animals:
1: fox
2: elephant
3: wolf

Can someone think of a solution that would work for alert() as well?

Upvotes: 0

Views: 243

Answers (2)

desrev3r
desrev3r

Reputation: 51

better use console.table() if you have an array of objects, dude

something like that:

const list = [{name: 'john', age: 10}, {name: 'misha', age: 24},{name: 'aaron', age: 50},]
console.table(Object.values(list))

Upvotes: 0

Colin Hale
Colin Hale

Reputation: 870

Maybe you could do it like this:

    let animals = ["fox", "elephant", "wolf"];

    let str = "List of animals:\n"
    for (let animal of animals) {
        let itemNum = animals.indexOf(animal) + 1;
        str += `${itemNum}: ${animal}\n`
    }

    alert(str)

Upvotes: 2

Related Questions