In JS if you would like to split user entry into an array what is the best way of going about it?
For example:
entry = prompt("Enter your name")
for (i=0; i<entry.length; i++)
{
entryArray[i] = entry.charAt([i]);
}
// entryArray=['j', 'e', 'a', 'n', 's', 'y'] after loop
Perhaps I'm going about this the wrong way - would appreciate any help!
You can try this:
var entryArray = Array.prototype.slice.call(entry)
ES6 is quite powerful in iterating through objects (strings, Array, Map, Set). Let's use a Spread Operator to solve this.
ES6 :
Do you care for non-English names? If so, all of the presented solutions (.split(''), [...str], Array.from(str), etc.) may give bad results, depending on language:
Consider using the grapheme-splitter library for a clean standards-based split: https://github.com/orling/grapheme-splitter
Use the
.split()
method. When specifying an empty string as the separator, thesplit()
method will return an array with one element per character....and also for those who like literature in CS.