博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在JavaScript中获取字符串数组的字符串?
阅读量:3579 次
发布时间:2019-05-20

本文共 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','!']


#1楼

参考:


#2楼

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 演示


#3楼

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功能之一来正确处理这些字符序列。

Spread-operator ( by insertusernamehere) Spread-operator(已由insertusernamehere )

> [...'𝟘𝟙𝟚𝟛'][ '𝟘', '𝟙', '𝟚', '𝟛' ]

> 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. 然而,这似乎不适用于无与伦比的低代理人。

Test all in your browser: 在浏览器中测试所有内容:

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-\퟿\-\]|[\?-\?][\?-\?]|[\?-\?](?![\?-\?])|(?:[^\?-\?]|^)[\?-\?]))/)


#4楼

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. 不一定是对或错,只是另一种选择。


#5楼

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))


#6楼

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中引入。

Reference 参考

转载地址:http://wmlgj.baihongyu.com/

你可能感兴趣的文章
off-by-one
查看>>
ctf-pwn的一些小技巧
查看>>
POJ 1915 Knight Moves
查看>>
Git 撤销修改
查看>>
Git 删除文件
查看>>
Git与远程仓库关联以及关联错误解决方法
查看>>
[HDU] 平方和与立方和
查看>>
[HDU 2096] 小明A+B
查看>>
[HDU 2520] 我是菜鸟,我怕谁(不一样的for循环)
查看>>
[HDU 1215] 七夕节(求因子,不超时)
查看>>
[POJ 1915] Knight Moves
查看>>
Memcache技术精华
查看>>
Redis详解入门篇
查看>>
php开启redis扩展包与redis安装
查看>>
php使用openssl来实现非对称加密
查看>>
pdo如何防止 sql注入
查看>>
myisam和innodb的区别
查看>>
MySQL建表规范与注意事项(个人精华)
查看>>
JDK8接口的新特性
查看>>
synchronized的局限性与lock的好处
查看>>