【问题标题】:Is it possible to Output forEach results horizontally?是否可以水平输出 forEach 结果?
【发布时间】:2021-04-10 17:47:09
【问题描述】:

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

电流输出

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

预期输出

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

【问题讨论】:

  • console.log 不会那样做。每个输出都会自动放在一个新行上。您可以执行 console.log(a, b, c, d, ...) 将它们放在同一行,但这在 a for each 的上下文中不起作用。您最好的选择是将它们连接成一个字符串,一旦循环完成就记录下来。 More here
  • 对不起,我是个新手,我才在编程学校学习了 12 周。只是想知道你能做什么,不能做什么,很抱歉提出被否决的问题。

标签: javascript methods foreach


【解决方案1】:

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

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

console.log(joinedList);

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

【讨论】:

  • 感谢您的回复,我不确定您是否可以在每个循环中使用 .join,但经过反馈后我很确定您不能。
【解决方案2】:

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

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

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

在这里了解更多关于reduce函数的信息Array.prototype.reduce()

【讨论】:

  • 感谢您的回复,这个reducer对我来说是新概念,我会研究一下这段代码,看看我是否能更好地理解它!
猜你喜欢
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2018-06-21
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
相关资源
最近更新 更多