如何在JavaScript中获取字符串数组的字符串?

本文翻译自:How do you get a string to a character array in JavaScript?

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楼

参考:https://stackoom.com/question/J52X/如何在JavaScript中获取字符串数组的字符串


#2楼

The spread Syntax spread语法

You can use the spread syntax , an Array Initializer introduced in ECMAScript 2015 (ES6) standard : 您可以使用扩展语法 ,即ECMAScript 2015(ES6)标准中引入的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 ECMAScript ES6 compatibility table . 检查ECMAScript ES6兼容性表


Further reading 进一步阅读

spread is also referenced as " splat " (eg in PHP or Ruby or as " scatter " (eg in Python ). spread也被称为“ splat ”(例如在PHPRuby中或作为“ scatter ”(例如在Python中 )。


Demo 演示

Try before buy 买前先试试


#3楼

Since this question is originally asked more than five years ago, people are still misopetating this type of task. 由于这个问题最初是在五年多前提出的, 人们仍然在误操作这类任务。 As hippietrail suggests , meder's answer can break surrogate pairs and misinterpret “characters.” For example: 正如hippietrail建议的那样meder的答案可以打破代理对并误解“角色”。例如:

// DO NOT USE THIS!
> '𝟘𝟙𝟚𝟛'.split('')
[ '�', '�', '�', '�', '�', '�', '�', '�' ]

I suggest using one of the following ES2015 features to correctly handle these character sequences. 我建议使用以下ES2015功能之一来正确处理这些字符序列。

Spread-operator ( already answered by insertusernamehere) Spread-operator(已由insertusernamehere 回答

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

Array.from Array.from

> Array.from('𝟘𝟙𝟚𝟛')
[ '𝟘', '𝟙', '𝟚', '𝟛' ]

RegExp u flag RegExp u旗帜

> '𝟘𝟙𝟚𝟛'.split(/(?=[\s\S])/u)
[ '𝟘', '𝟙', '𝟚', '𝟛' ]

Use /(?=[\\s\\S])/u instead of /(?=.)/u because . 使用/(?=[\\s\\S])/u而不是/(?=.)/u /(?=[\\s\\S])/u因为. does not match newlines . 与换行符不匹配

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 Babel ): 如果你还处于ES5.1时代(或者如果你的浏览器没有正确处理这个正则表达式 - 比如Edge),你可以使用这个替代方案(由Babel编译):

> '𝟘𝟙𝟚𝟛'.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; } 
 <div><input type="checkbox" id="nonBMP" checked /><label for="nonBMP">Codepoints above U+FFFF</label></div> <div><input type="checkbox" id="nl" checked /><label for="nl" >Newline</label></div> <div><input type="checkbox" id="high" /><label for="high" >Unmached high surrogate</label></div> <div><input type="checkbox" id="low" /><label for="low" >Unmached low surrogate</label></div> <button type="button" id="runTest">Run Test!</button> <table> <tr><td>str=</td> <td><div id="testString"></div></td></tr> <tr><th colspan="2">Wrong:</th></tr> <tr><td>str.split("")</td> <td><div id="splitEmpty"></div></td></tr> <tr><td>str.split(/(?=.)/u)</td> <td><div id="splitRegexDot"></div></td></tr> <tr><th colspan="2">Better:</th></tr> <tr><td>[...str]</td> <td><div id="spread"></div></td></tr> <tr><td>Array.from(str)</td> <td><div id="arrayFrom"></div></td></tr> <tr><td>str.split(/(?=[\\s\\S])/u)</td> <td><div id="splitRegex"></div></td></tr> <tr><td>str.split(/(?=(?:[\\0-\퟿\-\]|[\?-\?][\?-\?]|[\?-\?](?![\?-\?])|(?:[^\?-\?]|^)[\?-\?]))/)</td><td><div id="splitBabel"></div></td></tr> </table> 


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

Object.assign is described well at the MDN site. 在MDN站点上很好地描述了Object.assign。


#5楼

You can iterate over the length of the string and push the character at each position : 您可以迭代字符串的长度并在每个位置推送字符

 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 参考

Array.from Array.from

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值