How to convert Set to Array?

前端 未结 10 1086
余生分开走
余生分开走 2020-11-28 01:04

Set seems like a nice way to create Arrays with guaranteed unique elements, but it does not expose any good way to get properties, except for generator [Set

10条回答
  •  借酒劲吻你
    2020-11-28 01:38

    if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using for...of, or similar ?

    Indeed, there are several ways to convert a Set to an Array:

    using Array.from

    let array = Array.from(mySet);
    

    Simply spreading the Set out in an array

    let array = [...mySet];
    

    The old fashion way, iterating and pushing to a new array (Sets do have forEach)

    let array = [];
    mySet.forEach(v => array.push(v));
    

    Previously, using the non-standard, and now deprecated array comprehension syntax:

    let array = [v for (v of mySet)];
    

提交回复
热议问题