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);
JavaScript array initialization "use strict"; const nums = [1, 2, 3, 4, 5]; console. log(nums); The example creates a simple array in JavaScript. const nums = [1, 2, 3, 4, 5];
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
The console. log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.
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"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With