I have a string like "car;bus;airplane;bike"
what is the fastest way to convert it into a set in 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
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:
const theString = "car;bus;airplane;bike";
const theSet = new Set(theString.split(";"));
You can use the Set
constructor:
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.
You said "fastest" but all of the answers to date have used strings that they split into arrays and passed into the Set
constructor. 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(';')); console.log(x);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.