2011-11-02 147 views
25

在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 

也許我要對此錯誤的方式 - 希望得到任何幫助!

回答

45

使用.split()方法。當指定空字符串作爲分隔符時,split()方法將返回一個數組,每個字符包含一個元素。

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

請勿使用'.split('')'。請參閱http://stackoverflow.com/a/38901550/112731 –

6

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

2

你可以試試這個:

var entryArray = Array.prototype.slice.call(entry)

+2

請參閱[http://jsperf.com/string-to-array-of-characters](http://jsperf.com/string-to-array -of-字符)。 – XP1

7

ES6:

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

...和誰也爲那些喜歡在CS文獻。

array = Array.from(entry); 
1

您是否在意非英文名?如果是這樣,所有提出的解決方案(.split( ''),[... STR],Array.from(STR)等)可能會糟糕的結果,這取決於語言:

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

考慮使用字形分隔符庫進行乾淨的基於標準的分割: https://github.com/orling/grapheme-splitter