最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does an array embedded in a template literal not render inside square brackets? - Stack Overflow

programmeradmin2浏览0评论

When i try to put an array into a JavaScript array, a la,

> `${[1,2,3]}`

I get back this

'1,2,3'

and not

'[1,2,3]'

in the latest Node & Chrome.

I am missing something incredibly obvious, but need it spelled out to me nevertheless : )

When i try to put an array into a JavaScript array, a la,

> `${[1,2,3]}`

I get back this

'1,2,3'

and not

'[1,2,3]'

in the latest Node & Chrome.

I am missing something incredibly obvious, but need it spelled out to me nevertheless : )

Share Improve this question edited Dec 26, 2024 at 18:25 dumbass 27.2k4 gold badges36 silver badges73 bronze badges asked Jun 14, 2017 at 13:50 user3264325user3264325 2371 gold badge2 silver badges9 bronze badges 4
  • 3 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Andrew Li Commented Jun 14, 2017 at 13:51
  • You are getting the string interpretation of an array, so a join with comma separated values, change it to `[${[1, 2, 3]}]` should do it – Icepickle Commented Jun 14, 2017 at 13:52
  • 1 what ever object you use, its toString() gets called. Array.toString() returns a string of comma separated items of the array. – bugs_cena Commented Jun 14, 2017 at 14:12
  • I'm missing why you would expect this to get that non-obvious result? Template literals are not JSON.stringify. – Bergi Commented Jun 14, 2017 at 17:28
Add a comment  | 

3 Answers 3

Reset to default 8

You should use JSON.stringify(array) It can help you to predict conversion to the string any arrays in this array.

const array = [["expected","test",1],0];
const arrayStr = JSON.stringify(array);
const templateResAsString = `${array}`; // expected,test,1,0
const templateResAsarray = `${arrayStr}`; // [["expected","test",1],0]

By the default, the values that are interpolated into a template literal are converted to their string representation.

For objects that means calling their .toString() method. The string representation of an array is simply a comma separated list of the strings representation of its elements, without leading [ or trailing ]:

console.log(
  [1,2,3].toString()
);

Consolodiated list including above answers:

const arr = [1,2,3,4,5,'foo','bar','baz']


console.log(JSON.stringify(arr));
console.log(JSON.stringify(arr, null, 2));
console.log(arr.toString());
console.log(`${arr}`);
console.log(arr.join('\n'));

Good Luck...

发布评论

评论列表(0)

  1. 暂无评论