如何 console.log 数组中的每个元素?

Cod*_*yes 6 javascript arrays

我在解决与 forEach 方法相关的问题时遇到了麻烦。我已经尝试了所有我能想到的编写这段代码的方法,但问题一每次仍然是错误的。

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);
Run Code Online (Sandbox Code Playgroud)

Mah*_*Ali 4

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

您需要将回调传递给forEach()回调内的第一个元素,该元素将是其迭代的数组元素。只需记录一下即可。

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

箭头函数可能会让您感到困惑。正常功能的话会是

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

  • @CodyHayes 如果您对答案感到满意,请考虑接受答案。 (2认同)
  • @FareedAlnamrouti 那行不通。`forEach` 传递其他参数,这些参数都会被记录。 (2认同)