String.ToCharArray() equivalent on JavaScript?
Using Array.from is probably more explicit.
Array.from("012345").join(',') // returns "0,1,2,3,4,5"
Array.from
This is a much simpler way to do it:
"012345".split('').join(',')
The same thing, except with comments:
"012345".split('') // Splits into chars, returning ["0", "1", "2", "3", "4", "5"]
.join(',') // Joins each char with a comma, returning "0,1,2,3,4,5"
Notice that I pass an empty string to split()
. If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.
Alternatively you could pass nothing to join()
and it'd use a comma by default, but in cases like this I prefer to be specific.
Don't worry about speed — I'm sure there isn't any appreciable difference. If you're so concerned, there isn't anything wrong with a loop either, though it might be more verbose.
Maybe you could use the "Destructuring" feature:
let str = "12345";
//convertion to array:
let strArr = [...str]; // strArr = ["1", "2", "3", "4", "5"]