问题描述
嗨,我想知道如何水平而不是垂直返回数组的输出我尝试了几种不同的方法,但我无法让它工作。我知道您可以使用 .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()