I have an array that could contain Symbol() item. Array.toSring brings an exception.
const s = [10, 'abc', Symbol('test')].toString(); // this throws an exception
console.log([10, 'abc', Symbol('test')]); // this works
What is the best way to convert such array to a string (like console.log does)?
.map
the array, calling toString
on each symbol first:
const s = [10, 'abc', Symbol('test')]
.map(val => typeof val === 'symbol' ? val.toString() : val)
.join(',');
console.log(s);
To turn a Symbol into a string, you have to do so explicitly.
Calling toString
on a symbol is permitted, because that invokes Symbol.prototype.toString().
In contrast, trying to turn the Symbol into a string implicitly, like with Array.prototype.join
, (or Array.prototype.toString
, which internally calls Array.prototype.join
, or +
, etc), invokes the ToString operation, which throws when the argument is a Symbol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With