在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 becauseforEachexpects a callback function as its argument, not the result ofjoin()..push(paragraph)doesn't make sense here—push()is an array method, butparagraphis 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:
- We start with an empty string
paragraph. - For each word in the array, we use the
indexparameter fromforEachto 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. - We append each word to the
paragraphstring one by one. - 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_
相关产品推荐
相关产品推荐

