如何在JavaScript中将字符串转换为字符数组?
我在考虑获取一个字符串,比如"Hello world!"到数组 [' H ', ' e ', ' l ', ' l ', ' o ', ' ', ' w ', ' o ', ' r ', ' l ', ' d ', ' !']
如何在JavaScript中将字符串转换为字符数组?
我在考虑获取一个字符串,比如"Hello world!"到数组 [' H ', ' e ', ' l ', ' l ', ' o ', ' ', ' w ', ' o ', ' r ', ' l ', ' d ', ' !']
当前回答
Array.prototype.slice也会做同样的工作。
const result = Array.prototype.slice。调用(“Hello world !”); console.log(结果);
其他回答
它已经是:
我的线= 'foobar'; 控制台日志(mystring [0]);// Outputs 'f' 控制台日志(mystring [3]);// Outputs 'b'
或者对于更老的浏览器友好版本,使用:
Var mystring = 'foobar'; console.log (mystring.charAt (3));//输出'b'
你也可以使用Array.from。
var m = "Hello world!"; console.log (Array.from (m))
这个方法已经在ES6中引入。
参考
Array.from
ES6将字符串按字符分割为数组的方法是使用展开操作符。它既简单又漂亮。
array = [...myString];
例子:
让myString = "Hello world!" array =[…myString]; console.log(数组); //另一个例子: console.log([…“另一个分割文本”]);
简单的回答是:
让STR = '这是字符串,长度是>26'; console.log([…str));
这个怎么样?
function stringToArray(string) {
let length = string.length;
let array = new Array(length);
while (length--) {
array[length] = string[length];
}
return array;
}