如何在JavaScript中将字符串转换为字符数组?

我在考虑获取一个字符串,比如"Hello world!"到数组 [' H ', ' e ', ' l ', ' l ', ' o ', ' ', ' w ', ' o ', ' r ', ' l ', ' d ', ' !']


当前回答

它已经是:

我的线= 'foobar'; 控制台日志(mystring [0]);// Outputs 'f' 控制台日志(mystring [3]);// Outputs 'b'

或者对于更老的浏览器友好版本,使用:

Var mystring = 'foobar'; console.log (mystring.charAt (3));//输出'b'

其他回答

你可以遍历字符串的长度,并将字符推到每个位置:

const str = 'Hello World'; const stringToArray = (text) => { Var chars = []; For (var I = 0;I < text.length;我+ +){ [我]chars.push(文本); } 返回字符 } console.log (stringToArray (str))

一种可能是:

console.log([1, 2, 3].map(e => Math.random().toString(36).slice(2)).join('').split('').map(e => Math.random() > 0.5 ? e.toUpperCase() : e).join(''));

简单的回答是:

让STR = '这是字符串,长度是>26'; console.log([…str));

它已经是:

我的线= 'foobar'; 控制台日志(mystring [0]);// Outputs 'f' 控制台日志(mystring [3]);// Outputs 'b'

或者对于更老的浏览器友好版本,使用:

Var mystring = 'foobar'; console.log (mystring.charAt (3));//输出'b'

这是一个老问题,但我遇到了另一个尚未列出的解决方案。

你可以使用对象。指定函数以获得所需的输出:

var output =对象。assign([], "Hello, world!"); console.log(输出); / / [' H ', ' e ', ' l ', ' l ', ' o ', ',', ' ', ' w”、“o”、“r”、“l”、“d”、“!']

不一定是对与错,只是另一种选择。

对象。分配在MDN站点上描述得很好。