如何在控制台打印数组中的每个元素?

6

我在涉及forEach方法的这个问题上遇到了困难。 我尝试了我能想到的所有编写代码的方式,但问题1每次都是错误的。

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

1
请勿发布外部链接。在此处编辑并添加您的代码。 - Maheer Ali
1
这个链接已经失效了(至少对我来说是这样)。 - Jack Bashford
1
链接需要我登录。 - Snel23
names.forEach(function(item) { console.log(item); }) - j08691
1
我看到你代码中唯一的问题是,你没有在 exerciseOne() 方法内部实现逻辑。 - Shidersz
2个回答

4

在你的代码中,你正在记录整个数组。使用数组上的forEach方法并记录元素。

你需要向forEach()传递一个回调函数,回调函数内的第一个参数将是正在迭代的数组元素。只需记录该元素即可。

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

箭头函数可能会让您感到困惑。与普通函数不同,它将是:

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


你救了我的命,我永远感激不尽! - Cody Hayes
1
@CodyHayes 如果您对答案满意,请考虑接受它。 - Maheer Ali
console.log是一个函数,你可以使用names.forEach(console.log) - Fareed Alnamrouti
2
@FareedAlnamrouti 那样行不通。forEach 会传递其他参数,所有参数都将被记录。 - Mark

2

每次使用console.log作为回调函数,记录第一个参数(当前项):

最初的回答

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接