[英]Unique characters in JavaScript
function unique_char(string) { return String.prototype.concat(...new Set(string)); } console.log(unique_char("Hellooooooooooooo"));
谁能帮我理解 .concat 一个新的 Set 将如何返回独特的字符? 我以为 .concat 会添加 ,为什么在新 Set 之前有一个传播操作......?
1)
new Set(string)
由于 JS 中的strings
是可迭代的,因此Set
将字符串作为输入并为您提供一组独特的字符。
2)
String.prototype.concat(...new Set(string)
concat() 方法将字符串
arguments
连接到调用字符串并返回一个新字符串。One or more strings
连接到 str。 - MDN
因此concat
将逐个字符地append
其append
到单个字符串中
function unique_char(string) { const set = new Set(string); console.log(...set); return String.prototype.concat(...set); } console.log(unique_char("Hellooooooooooooo"));
所以让我们把这个命令一分为二:
new Set(string)
=> 这将从new Set(string)
创建一个新的 Set 并且每个字符只保留一次...
用于将集合“转换”为数组(集合是可迭代的)String.prototype.concat
用于连接扩展运算符返回的数组中的所有字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.