如何在JavaScript中将字符串转换为字符数组?
我想获取一个像
我想获取一个像
"Hello world!"
这样的字符串,并将其转换为数组['H','e','l','l','o','','w','o','r','l','d','!']
"Hello world!"
这样的字符串,并将其转换为数组['H','e','l','l','o','','w','o','r','l','d','!']
let str = 'this is string, length is >26';
console.log([...str]);
(参考该链接)
const str = 'Hello World';
const stringToArray = (text) => {
var chars = [];
for (var i = 0; i < text.length; i++) {
chars.push(text[i]);
}
return chars
}
console.log(stringToArray(str))
"".charAt(0)
将返回一个无法使用的字符。 - KyleMit.split("")
进行了大量优化。虽然循环在Chrome和Firefox中具有类似的性能,但是对于小型和大型输入,Firefox中的split速度显着更快。 - Luxstr = ''
,它会出错。 - Arnis Juragafunction stringToArray(string) {
let length = string.length;
let array = new Array(length);
while (length--) {
array[length] = string[length];
}
return array;
}
Array.prototype.slice 也可以完成这项工作。
const result = Array.prototype.slice.call("Hello world!");
console.log(result);
一种可能性是下面这个:
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(''));