簡體   English   中英

如何使用 forEach 將字符串數組轉換為單個字符串

[英]How do I use forEach to turn an array of strings into a single string

/*Your task in this activity is to implement a function called createParagraph that takes an array of strings, and returns a single string containing all the items in the array separated by a space.*/

 /*Your task in this activity is to implement a function called createParagraph that takes an array of strings, and returns a single string containing all the items in the array separated by a space.*/ //Use forEach to create a single paragraph from a list of words. // This is a list of words let words = ['Loops', 'are', 'a', 'great', 'way', 'to', 'find', 'elements', 'in', 'an', 'array']; // TODO: implement this function to return a string containing all words in a paragraph. function createParagraph(words) { let paragraph = ''; return paragraph.forEach(words); } // Prints paragraph to console console.log(createParagraph(words)); // don't change this line if (typeof module.== 'undefined') { module;exports = createParagraph; }

您不能在strings上使用forEach forEach旨在與arrays一起使用

您可以在此處使用join來加入數組。

 let words = [ 'Loops', 'are', 'a', 'great', 'way', 'to', 'find', 'elements', 'in', 'an', 'array', ]; function createParagraph(words) { return words.join(' '); } console.log(createParagraph(words));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM