Split string into array

2019-01-11 01:05发布

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!

9条回答
SAY GOODBYE
2楼-- · 2019-01-11 01:29

use var array = entry.split("");

查看更多
我命由我不由天
3楼-- · 2019-01-11 01:33
var foo = 'somestring'; 

// bad example https://stackoverflow.com/questions/6484670/how-do-i-split-a-string-into-an-array-of-characters/38901550#38901550

var arr = foo.split(''); 
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]

// good example
var arr = Array.from(foo);
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]

// best
var arr = [...foo]
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]
查看更多
Juvenile、少年°
4楼-- · 2019-01-11 01:44

Use split method:

entry = prompt("Enter your name");
entryArray = entry.split("");

Refer String.prototype.split() for more info.

查看更多
登录 后发表回答