How do I split a string into an array of characters?Do NOT use .split('')

2022-08-30 02:19:14
var s = "overpopulation";
var ar = [];
ar = s.split();
alert(ar);

I want to string.split a word into array of characters.

The above code doesn't seem to work - it returns "overpopulation" as Object..

How do i split it into array of characters, if original string doesn't contain commas and whitespace?


答案 1

You can split on an empty string:

var chars = "overpopulation".split('');

If you just want to access a string in an array-like fashion, you can do that without :split

var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
    console.log(s.charAt(i));
}

You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).

var s = "overpopulation";

console.log(s[3]); // logs 'r'

答案 2

Old question but I should warn:

Do NOT use .split('')

You'll get weird results with non-BMP (non-Basic-Multilingual-Plane) character sets.

Reason is that methods like and only respect the characters with a code point below 65536; bec. higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters..split().charCodeAt()

'