将字符串分割为数组

56

如果你想要在JS中将用户输入分割成一个数组,最好的方法是什么?

举个例子:

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

也许我走了错误的路——希望能得到任何帮助!

10个回答

93
使用 .split() 方法。当指定空字符串作为分隔符时,split() 方法将返回一个数组,每个元素对应一个字符。
entry = prompt("Enter your name")
entryArray = entry.split("");

12
不要使用.split('')。请参考https://dev59.com/w2w15IYBdhLWcg3wo9Rx#38901550。 - Onur Yıldırım

17

ES6 :

const array = [...entry]; // entry="i am" => array=["i"," ","a","m"]

12

使用 var array = entry.split("");


10

你是否关注非英语名称?如果是,所有提供的解决方案(.split(''),[...str],Array.from(str)等)可能会根据语言而产生错误结果:

"प्रणव मुखर्जी".split("") // the current president of India, Pranab Mukherjee
// returns ["प", "्", "र", "ण", "व", " ", "म", "ु", "ख", "र", "्", "ज", "ी"]
// but should return ["प्", "र", "ण", "व", " ", "मु", "ख", "र्", "जी"]

考虑使用grapheme-splitter库进行基于标准的干净分割:

https://github.com/orling/grapheme-splitter

5
var foo = 'somestring'; 

// bad example https://dev59.com/w2w15IYBdhLWcg3wo9Rx#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"]

4

使用 split 方法:

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

请参阅String.prototype.split()获取更多信息。


3
您可以尝试这样做:
var entryArray = Array.prototype.slice.call(entry)

2
请查看http://jsperf.com/string-to-array-of-characters。 - XP1

3

...也适用于那些喜欢计算机科学文献的人。

array = Array.from(entry);

2

ES6在迭代对象(字符串、数组、Map、Set)方面非常强大。让我们使用扩展运算符来解决这个问题。

entry = prompt("Enter your name");
var count = [...entry];
console.log(count);

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接