met*_*lah 34 javascript string string-split
在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
Run Code Online (Sandbox Code Playgroud)
也许我会以错误的方式解决这个问题 - 非常感谢任何帮助!
Jam*_*ill 64
使用该.split()方法.将空字符串指定为分隔符时,该split()方法将返回一个数字,每个字符包含一个元素.
entry = prompt("Enter your name")
entryArray = entry.split("");
Run Code Online (Sandbox Code Playgroud)
const array = [...entry]; // entry="i am" => array=["i"," ","a","m"]
Run Code Online (Sandbox Code Playgroud)
您喜欢非英文名称吗?如果是这样,根据语言,所有呈现的解决方案(.split(''),[... str],Array.from(str)等)可能会给出不好的结果:
"????? ???????".split("") // the current president of India, Pranab Mukherjee
// returns ["?", "?", "?", "?", "?", " ", "?", "?", "?", "?", "?", "?", "?"]
// but should return ["??", "?", "?", "?", " ", "??", "?", "??", "??"]
Run Code Online (Sandbox Code Playgroud)
考虑使用grapheme-splitter库进行干净的基于标准的拆分:https : //github.com/orling/grapheme-splitter
var foo = 'somestring';
Run Code Online (Sandbox Code Playgroud)
// bad example /sf/ask/453926931/#38901550
var arr = foo.split('');
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]
Run Code Online (Sandbox Code Playgroud)
// good example
var arr = Array.from(foo);
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]
Run Code Online (Sandbox Code Playgroud)
// best
var arr = [...foo]
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]
Run Code Online (Sandbox Code Playgroud)