You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript中使用forEach拼接数组元素

Solution: Use forEach to Concatenate Array into a Single String

Got it, let's fix this up for you step by step. First, let's break down why your initial attempt didn't work:

  • words.forEach(words.join(' ')) is incorrect because forEach expects a callback function as its argument, not the result of join().
  • .push(paragraph) doesn't make sense here—push() is an array method, but paragraph is a string, not an array.

Here's the corrected implementation that follows your requirements (no join(), using forEach):

// 这是一个单词列表
let words = ['Loops', 'are', 'a', 'great', 'way', 'to', 'find', 'elements', 'in', 'an', 'array'];
// TODO: 实现此函数以返回包含所有单词的段落字符串
function createParagraph(words) {
  let paragraph = '';
  // 使用forEach遍历每个单词
  words.forEach((word, index) => {
    // 不是第一个单词的话,先加空格分隔
    if (index !== 0) {
      paragraph += ' ';
    }
    // 把当前单词拼接到段落里
    paragraph += word;
  });
  return paragraph;
}
// 在控制台打印段落
console.log(createParagraph(words)); // 请勿修改此行
if (typeof module !== 'undefined') {
  module.exports = createParagraph;
}

How this works:

  1. We start with an empty string paragraph.
  2. For each word in the array, we use the index parameter from forEach to check if it's the first element. If it's not, we add a space before the word to avoid extra spaces at the start of the string.
  3. We append each word to the paragraph string one by one.
  4. Finally, we return the fully concatenated paragraph string.

This will produce the exact same result as words.join(' '), but strictly uses forEach as required.

内容的提问来源于stack exchange,提问作者roninroyal_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:07:46