微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否可以水平输出 forEach 结果?

如何解决是否可以水平输出 forEach 结果?

嗨,我想知道如何水平而不是垂直返回数组的输出我尝试了几种不同的方法,但我无法让它工作。我知道您可以使用 .join 而不是使用 foreach,但我想知道是否有使用 foreach 的方法。我也知道你可以将它输出为数组或对象,但输出中会有 {} 或 []。

const studentsRow1 = ["Rachelle","Jacob","Jerome","Greg","Matt","Walt"];

// Method 1
studentsRow1.forEach(function(student){
      console.log(student)

// Method 2
studentsRow1.forEach(student => console.log (`${student}`))

电流输出

雷切尔
雅各
杰罗姆
格雷格
马特
沃尔特

预期输出

雷切尔、雅各布、杰罗姆、格雷格、马特、沃尔特

解决方法

如果您只需要将数组输出为逗号分隔的字符串,则根本不需要循环,只需使用连接即可,正如您所提到的。

const studentsRow1 = ["Rachelle","Jacob","Jerome","Greg","Matt","Walt"];
const joinedList = studentsRow1.join(',');

console.log(joinedList);

// output: "Rachelle,Jacob,Jerome,Greg,Matt,Walt"
,

如果我明白你在说什么,你可以用reduce函数来实现

const studentsRow1 = ["Rachelle","Walt"];
const reducer = (accumulator,currentValue) => accumulator + ',' + currentValue;

console.log(studentsRow1.reduce(reducer));

在此处了解有关 reduce 函数的更多信息Array.prototype.reduce()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。