简体   繁体   English

JavaScript - 直接在多行字符串中循环遍历数组并包含值

[英]JavaScript - Loop Through Array Directly In Multi Line String and Include Values

Let's say I have an array called users.假设我有一个名为 users 的数组。

const users = ["userOne", "userTwo"];

Within an ES6 multi-line string, I would like to loop through the array and include the values of the users array within the multi-line string.在 ES6 多行字符串中,我想循环遍历数组并将users数组的值包含在多行字符串中。

I have tried giving it a go using the following code snippet:我尝试使用以下代码片段给它一个 go :

const data = `

Hello,

The following users exist within the users array:

- ${users.forEach((item) => item)},
`

The expected outcome I would like it something like this:预期的结果我希望它是这样的:

Hello,

The following users exist within the users array:

- userOne
- userTwo

What would I need to do to loop through the array and include the values within the string?我需要做什么来循环遍历数组并将值包含在字符串中?

You could map the items with some formatting.您可以使用某些格式对项目进行 map。

 const users = ["userOne", "userTwo"]; const data = `Hello, The following user${users.length > 1? 's': ''} exist within the user's array: ${users.map(item => `- ${item}`).join(',\n')}` console.log(data);

You could try:你可以试试:

 const users = ["userOne", "userTwo"]; const data = `Hello, The following users exist within the users array: ${users.map((user) => { return '- ' + user + '\n'; })}` console.log(data);

Use map instead of forEach and join with delimitter '- '使用map代替forEach并加入分隔符'- '

 const users = ["userOne", "userTwo"]; const data = ` Hello, The following users exist within the user's array: - ${users.map(item => item +'\n').join('- ')}`; console.log(data)

Using users.map() instead of users.forEach() , because map returns a new array, forEach doesn't.使用users.map()而不是users.forEach() ,因为map返回一个新数组,而forEach不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM