带字符串插值的字符串数组

array of strings with string interpolation

我有一个字符串数组,如下所示

const array = ["string1", "string2", "string3"];
const total = 10000;

我有一个 url 具有如下所示的字符串插值

const url = `http://localhost:8080/total=${total}&array=${array}`

这让我返回以下内容

http://localhost:8080/total=10000&array=[string1, string2, string3]

如何使字符串数组与 JS 的字符串插值一起使用。

预期结果应该类似于

http://localhost:8080/total=10000&array=["string1", "string2", "string3"]

感谢任何帮助

使用JSON.stringify()将数组转换为字符串:

const array = ["string1", "string2", "string3"];
const total = 10000;

const url = `http://localhost:8080/total=${total}&array=${JSON.stringify(array)}`

console.log(url)

As you might need to use encodeURIComponent() 转义带有保留字符的字符串。非保留字符为 A-Z a-z 0-9 - _ . ! ~ * ' ( ):

const array = ["string1", "string2", "string3"];
const total = 10000;

const url = `http://localhost:8080/total=${total}&array=${encodeURIComponent(JSON.stringify(array))}`

console.log(url)