如何在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 ', ' !']
当前回答
一种可能是:
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(''));
其他回答
ES6将字符串按字符分割为数组的方法是使用展开操作符。它既简单又漂亮。
array = [...myString];
例子:
让myString = "Hello world!" array =[…myString]; console.log(数组); //另一个例子: console.log([…“另一个分割文本”]);
你可以遍历字符串的长度,并将字符推到每个位置:
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(''));
这个怎么样?
function stringToArray(string) {
let length = string.length;
let array = new Array(length);
while (length--) {
array[length] = string[length];
}
return array;
}
简单的回答是:
让STR = '这是字符串,长度是>26'; console.log([…str));