简体   繁体   English

用分隔的单词转换字符串的最快方法是什么? 成一套?

[英]what is the fastest way to convert a string with words separated by ; into a set?

I have a string like "car;bus;airplane;bike"我有一个字符串,例如“汽车;公共汽车;飞机;自行车”

what is the fastest way to convert it into a set in JavaScript JSX?将其转换为 JavaScript JSX 中的集合的最快方法是什么?

Is there something like:有没有类似的东西:

"car;bus;airplane;bike".split(';').toSet()?

So the set will have 'car', 'bus', 'airplane', 'bike' as elements所以这个集合将有“汽车”、“公共汽车”、“飞机”、“自行车”作为元素

you can use 您可以使用

let x = new Set("car;bus;airplane;bike".split(';'));

Javscript Set can be initialised as Javscript集可以初始化为

new Set([iterable]);

you can initialise it with an iterable object 你可以用一个可迭代的对象来初始化它

使用:新Set(“ car; bus; airplane; bike” .split(';'))

Since you can construct a Set from an itrerable, you could go for: 由于可以从迭代器构造Set ,因此可以进行以下操作:

const theString = "car;bus;airplane;bike";
const theSet = new Set(theString.split(";"));

You can use the Set constructor: 您可以使用Set构造函数:

 s = new Set("car;bus;airplane;bike".split(';')) console.log(s.size); console.log(s); 

The constructor can take any iterable and convert the objects to be the set's elements. 构造函数可以采用任何可迭代的形式,并将对象转换为集合的元素。

Note that stackoverflow's snippet will not show the log of s but if you use chrome you can open the console and find the relevant result there. 请注意,stackoverflow的代码段不会显示s的日志,但是如果您使用chrome,则可以打开控制台并在此处找到相关的结果。

You said "fastest" but all of the answers to date have used strings that they split into arrays and passed into the Set constructor. 您说的是“最快”,但是到目前为止,所有答案都使用了将其拆分为数组并传递给Set构造函数的字符串。 Cut out the middleman if you really meant "fastest": 如果您的意思是“最快”,请切掉中间人:

 const s = new Set(["car","bus","airplane","bike"]); console.log(s.size); console.log(s.has("bus")); 

Not that the speed of this operation is likely to be significant. 并不是说此操作的速度可能很重要。

const x = new Set('car;bus;bike'.split(';')); const x = new Set('car;bus;bike'.split(';')); console.log(x);控制台.log(x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM