gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:56:34 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com