51

在 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

也许我正在以错误的方式解决这个问题 - 将不胜感激任何帮助!

4

10 回答 10

88

使用.split()方法。当指定一个空字符串作为分隔符时,该split()方法将返回一个每个字符一个元素的数组。

entry = prompt("Enter your name")
entryArray = entry.split("");
于 2011-11-02T11:44:03.287 回答
15

ES6:

const array = [...entry]; // entry="i am" => array=["i"," ","a","m"]
于 2016-09-14T16:18:30.913 回答
11

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

于 2011-11-02T11:42:25.403 回答
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

于 2017-07-21T13:31:31.870 回答
5
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"]
于 2018-05-18T14:48:09.403 回答
3

使用split方法:

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

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

于 2011-11-02T11:43:32.373 回答
3

你可以试试这个:

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

于 2011-11-02T11:54:36.853 回答
3

...也适用于那些喜欢 CS 文学的人。

array = Array.from(entry);
于 2016-11-06T11:07:48.250 回答
2

ES6 在遍历对象(字符串、数组、映射、集合)方面非常强大。让我们使用扩展运算符来解决这个问题。

entry = prompt("Enter your name");
var count = [...entry];
console.log(count);
于 2018-09-08T17:47:16.227 回答
0

你可以这样试试:

let entry = prompt("Enter your name") 
let entryArray = entry.split('')
console.log(entryArray)

这是小提琴 https://jsfiddle.net/swapanil/Lp1arvqc/17/

于 2019-12-27T07:18:38.330 回答