[英]JavaScript passing String Array to String literal
I want to pass Array of string values to a string literal as follows我想将字符串值数组传递给字符串文字,如下所示
Code:代码:
var array = ['1','2556','3','4','5'];
...
...
var output = `
<scr`+`ipt>
window.stringArray = [`+ array +`]
</scr`+`ipt>
`
Output: Output:
<script>
window.stringArray = [1,2556,3,4,5]
</script>
Desired Output:所需 Output:
<script>
window.stringArray = ['1','2556','3','4','5']
</script>
I've tried to not string the arrays and string it inside the multiline string, but the values are too long for int to handle and it breaks eg [888555985744859665555] this will turn into [888555985744859665500] and it's a push on the memory, easy to use string regardless!我尝试不将 arrays 串起来并将其串在多行字符串中,但是值太长而 int 无法处理并且它会中断例如 [888555985744859665555] 这将变成 [888555985744859665500] 并且它是对 memory 的推动,简单无论如何都要使用字符串! Next I've tried to use map function within the inline string like this
接下来我尝试在内联字符串中使用 map function 像这样
`[`+ array.map(String) +`]`
I can't add any more lines to the output string mentioned above, code can be modified within the one line or added above it!上面提到的output字符串我不能再加行了,代码可以在一行内修改,也可以在上面加!
You can stringify
the array.您可以对数组进行
stringify
。 In addition just escape the /
instead of using concatenation on the tag name - it's easier to read, and more efficient .此外,只需转义
/
而不是在标签名称上使用连接 - 它更易于阅读,效率更高。
const array = ['1','2556','3','4','5']; const output = ` <script> window.stringArray = ${JSON.stringify(array)} <\/script> `; console.log(output);
Why not use JSON.stringify
?为什么不使用
JSON.stringify
? It works perfectly for your use case!它非常适合您的用例!
var array = ['1','2556','3','4','5']; var output = ` <scr`+`ipt> window.stringArray = `+ JSON.stringify(array) +`; </scr`+`ipt> `; console.log(output);
You can read more about the usage of JSON.stringify
on MDN .您可以在 MDN 上阅读更多关于
JSON.stringify
的用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.