How do you get a string to a character array in Ja

2019-01-02 19:49发布

How do you get a string to a character array in JavaScript?

I'm thinking getting a string like "Hello world!" to the array ['H','e','l','l','o',' ','w','o','r','l','d','!']

8条回答
泪湿衣
2楼-- · 2019-01-02 20:37

The spread Syntax

You can use the spread syntax, an Array Initializer introduced in ECMAScript 2015 (ES6) standard:

var arr = [...str];

Examples

function a() {
    return arguments;
}

var str = 'Hello World';

var arr1 = [...str],
    arr2 = [...'Hello World'],
    arr3 = new Array(...str),
    arr4 = a(...str);

console.log(arr1, arr2, arr3, arr4);

The first three result in:

["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]

The last one results in

{0: "H", 1: "e", 2: "l", 3: "l", 4: "o", 5: " ", 6: "W", 7: "o", 8: "r", 9: "l", 10: "d"}

Browser Support

Check the ECMAScript ES6 compatibility table.


Further reading

spread is also referenced as "splat" (e.g. in PHP or Ruby or as "scatter" (e.g. in Python).


Demo

Try before buy

查看更多
余生无你
3楼-- · 2019-01-02 20:39

It already is:

var mystring = 'foobar';

console.log(mystring[0]); // Outputs 'f'
console.log(mystring[3]); // Outputs 'b'

Or for a more older browser friendly version, use:

console.log(mystring.charAt(3)); // Outputs 'b'
查看更多
登录 后发表回答