简体   繁体   中英

How do I console.log every element in an array?

I'm having trouble with this question related to the forEach method. I've tried every way of writing this code out that I could think of but question one is still wrong every time.

function exerciseOne(names){

// Exercise One: In this exercise you will be given and array called names. 

// Using the forEach method and a callback as it's only argument, console log

// each of the names.
}


// MY CODE: 

function logNames(name){

  console.log(name);
}

 names.forEach(logNames);

In your code you are logging the whole array. Use forEach method on array and log the element.

You need to pass a callback to forEach() the first element inside callback will be the element of array thought which its iterating. Just log that.

 function exerciseOne(names){ names.forEach(x => console.log(x)); } exerciseOne(['John','peter','mart']) 

Arrow function may confuse you. With normal function it will be

 function exerciseOne(names){ names.forEach(function(x){ console.log(x) }); } exerciseOne(['John','peter','mart']) 

Just use console.log as the callback, logging the first parameter (the current item) each time:

 function exerciseOne(names) { names.forEach(name => console.log(name)); } exerciseOne(["Jack", "Joe", "John", "Bob"]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM