0

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?

Stefan
  • 969
  • 6
  • 9
  • So whats the problem with your current solution? – Stevetro Feb 10 '21 at 01:31
  • Does this answer your question? [Alert an array with while loop](https://stackoverflow.com/questions/47952326/alert-an-array-with-while-loop) – padaleiana Feb 10 '21 at 01:31
  • Nothing is wrong with this solution. I would like to have same logic just inside alert() method. How can I do it? And padaleiana nope, it doesn't.. – Stefan Feb 10 '21 at 01:38

2 Answers2

2

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)
Colin Hale
  • 824
  • 5
  • 11
0

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))

desrev3r
  • 51
  • 6