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条回答
疯言疯语
2楼-- · 2019-01-11 01:17

You can try this:

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

查看更多
地球回转人心会变
3楼-- · 2019-01-11 01:18

ES6 is quite powerful in iterating through objects (strings, Array, Map, Set). Let's use a Spread Operator to solve this.

entry = prompt("Enter your name");
var count = [...entry];
console.log(count);
查看更多
▲ chillily
4楼-- · 2019-01-11 01:22

ES6 :

const array = [...entry]; // entry="i am" => array=["i"," ","a","m"]
查看更多
不美不萌又怎样
5楼-- · 2019-01-11 01:22

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:

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

Consider using the grapheme-splitter library for a clean standards-based split: https://github.com/orling/grapheme-splitter

查看更多
一夜七次
6楼-- · 2019-01-11 01:24

Use the .split() method. When specifying an empty string as the separator, the split() method will return an array with one element per character.

entry = prompt("Enter your name")
entryArray = entry.split("");
查看更多
太酷不给撩
7楼-- · 2019-01-11 01:28

...and also for those who like literature in CS.

array = Array.from(entry);
查看更多
登录 后发表回答