gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:30:26 25 4
gpt4 key购买 nike

假设我有一个名为 users 的数组。

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

在 ES6 多行字符串中,我想遍历数组并将 users 数组的值包含在多行字符串中。

我尝试使用以下代码片段来尝试一下:

const data = `

Hello,

The following users exist within the users array:

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

我希望它的预期结果是这样的:

Hello,

The following users exist within the users array:

- userOne
- userTwo

要遍历数组并将值包含在字符串中,我需要做什么?

最佳答案

您可以使用某种格式映射项目。

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);

关于JavaScript - 直接在多行字符串中循环遍历数组并包含值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67055232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com