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 Answers
Reset to default 8You 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...
`[${[1, 2, 3]}]`
should do it – Icepickle Commented Jun 14, 2017 at 13:52toString()
gets called.Array.toString()
returns a string of comma separated items of the array. – bugs_cena Commented Jun 14, 2017 at 14:12JSON.stringify
. – Bergi Commented Jun 14, 2017 at 17:28