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

标签 javascript arrays

我遇到了与 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);

最佳答案

在您的代码中,您正在记录整个数组。在数组上使用 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'])

关于javascript - 我如何 console.log 数组中的每个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56051403/

相关文章:

python - 如何计算矩阵中每个单元格占列总和的比例?

c++ - C++对象数组中的奇怪数字

javascript - Chrome 刷新 "resubmit form data"提交 Null

JavaScript 正则表达式表情符号

javascript - 带有链接的 jQuery Catcomplete

c - C 中的数组声明和指针赋值

javascript - 如何访问 nodejs 插件中的包装对象属性

javascript - js.erb 正在渲染文本而不是 JS

c++ - C++头文件中定义字符数组

javascript - 在 Div 内显示 JavaScript 数组元素