【问题标题】:How do I use forEach to turn an array of strings into a single string如何使用 forEach 将字符串数组转换为单个字符串
【发布时间】:2022-01-15 05:15:16
【问题描述】:
/*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;
}

【问题讨论】:

  • 直接返回return words.join(' ');
  • 本课是否要求您使用 forEach?如果是这样,那么它是 words.forEach,并且该块将其参数附加到段落

标签: javascript arrays string if-statement foreach


【解决方案1】:

您不能在strings 上使用forEachforEacharrays 一起使用

你可以在这里使用join来加入一个数组。

let words = [
  'Loops',
  'are',
  'a',
  'great',
  'way',
  'to',
  'find',
  'elements',
  'in',
  'an',
  'array',
];

function createParagraph(words) {
  return words.join(' ');
}

console.log(createParagraph(words));

【讨论】:

  • 这显然是一项家庭作业,旨在教授如何遍历数组并手动构建段落。要求是使用forEach,你不应该只是把答案给学生。
猜你喜欢
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2015-02-19
  • 2015-11-24
  • 1970-01-01
  • 2011-06-18
相关资源
最近更新 更多