本文共 5532 字,大约阅读时间需要 18 分钟。
本文翻译自:
How do you get a string to a character array in JavaScript? 如何在JavaScript中获取字符串数组的字符串?
I'm thinking getting a string like "Hello world!"
我在想一个像"Hello world!"
这样的字符串"Hello world!"
to the array ['H','e','l','l','o',' ','w','o','r','l','d','!']
到数组['H','e','l','l','o',' ','w','o','r','l','d','!']
参考:
The spread
Syntax spread
语法
You can use the , an Array Initializer introduced in : 您可以使用 ,即引入的Array Initializer:
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 . 检查 。
Further reading 进一步阅读
spread
is also referenced as " splat
" (eg in or or as " scatter
" (eg in ). spread
也被称为“ splat
”(例如在或或作为“ scatter
”(例如在 )。
Demo 演示
Since this question is originally asked more than five years ago, people are still misopetating this type of task. 由于这个问题最初是在五年多前提出的, 人们仍然在误操作这类任务。 As , can break surrogate pairs and misinterpret “characters.” For example: 正如 , 可以打破代理对并误解“角色”。例如:
// DO NOT USE THIS!> '𝟘𝟙𝟚𝟛'.split('')[ '�', '�', '�', '�', '�', '�', '�', '�' ]
I suggest using one of the following ES2015 features to correctly handle these character sequences. 我建议使用以下ES2015功能之一来正确处理这些字符序列。
> [...'𝟘𝟙𝟚𝟛'][ '𝟘', '𝟙', '𝟚', '𝟛' ]
> Array.from('𝟘𝟙𝟚𝟛')[ '𝟘', '𝟙', '𝟚', '𝟛' ]
> '𝟘𝟙𝟚𝟛'.split(/(?=[\s\S])/u)[ '𝟘', '𝟙', '𝟚', '𝟛' ]
Use /(?=[\\s\\S])/u
instead of /(?=.)/u
because 使用/(?=[\\s\\S])/u
而不是/(?=.)/u
/(?=[\\s\\S])/u
因为 . 。
If you are still in ES5.1 era (or if your browser doesn't handle this regex correctly - like Edge), you can use this alternative (transpiled by ): 如果你还处于ES5.1时代(或者如果你的浏览器没有正确处理这个正则表达式 - 比如Edge),你可以使用这个替代方案(由编译):
> '𝟘𝟙𝟚𝟛'.split(/(?=(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/);[ '𝟘', '𝟙', '𝟚', '𝟛' ]
Note, that Babel tries to also handle unmatched surrogates correctly. 请注意,Babel试图正确处理不匹配的代理。 However, this doesn't seem to work for unmatched low surrogates. 然而,这似乎不适用于无与伦比的低代理人。
function run_test(){ str=document.getElementById('nonBMP').checked ? '𝟘_NL_𝟙_HIGH_𝟚_LOW_𝟛' : '0_NL_1_HIGH_2_LOW_3'; str=str.replace('_NL_' ,document.getElementById('nl' ).checked ? '\\n' : ''); str=str.replace('_HIGH_',document.getElementById('high').checked ? '𝟘'.charAt(0) : ''); str=str.replace('_LOW_' ,document.getElementById('low' ).checked ? '𝟘'.charAt(1) : ''); //wrap all examples into try{ eval(...) } catch {} to aloow script execution if some syntax not supported (for example in Internet Explorer) document.getElementById("testString" ).innerText=JSON.stringify(str); try { document.getElementById("splitEmpty" ).innerText=JSON.stringify(eval('str.split("")')); } catch(err) { } try { document.getElementById("splitRegexDot").innerText=JSON.stringify(eval('str.split(/(?=.)/u)')); } catch(err) { } try { document.getElementById("spread" ).innerText=JSON.stringify(eval('[...str]')); } catch(err) { } try { document.getElementById("arrayFrom" ).innerText=JSON.stringify(eval('Array.from(str)')); } catch(err) { } try { document.getElementById("splitRegex" ).innerText=JSON.stringify(eval('str.split(/(?=[\\\\s\\\\S])/u)')); } catch(err) { } try { document.getElementById("splitBabel" ).innerText=JSON.stringify(eval('str.split(/(?=(?:[\\\\0-\\\\\\-\\\]|[\\\?-\\\?][\\\?-\\\?]|[\\\?-\\\?](?![\\\?-\\\?])|(?:[^\\\?-\\\?]|^)[\\\?-\\\?]))/)')); } catch(err) { } } document.getElementById('runTest').onclick=run_test;
th, td { border: 1px solid black; padding: 4px; }
str= | |
Wrong: | |
---|---|
str.split("") | |
str.split(/(?=.)/u) | |
Better: | |
[...str] | |
Array.from(str) | |
str.split(/(?=[\\s\\S])/u) | |
str.split(/(?=(?:[\\0-\\-\]|[\?-\?][\?-\?]|[\?-\?](?![\?-\?])|(?:[^\?-\?]|^)[\?-\?]))/) |
This is an old question but I came across another solution not yet listed. 这是一个老问题,但我遇到了另一个尚未列出的解决方案。
You can use the Object.assign function to get the desired output: 您可以使用Object.assign函数来获取所需的输出:
var output = Object.assign([], "Hello, world!"); console.log(output); // [ 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!' ]
Not necessarily right or wrong, just another option. 不一定是对或错,只是另一种选择。
You can iterate over the length of the string and push the : 您可以迭代字符串的长度并推送 :
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))
You can also use Array.from
. 您也可以使用Array.from
。
var m = "Hello world!"; console.log(Array.from(m))
This method has been introduced in ES6. 这种方法已在ES6中引入。
转载地址:http://wmlgj.baihongyu.com/