简体   繁体   中英

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:

<script>
    window.stringArray = [1,2556,3,4,5]
</script>

Desired 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! Next I've tried to use map function within the inline string like this

`[`+ 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!

You can stringify the array. 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 ? 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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