How to convert Set to Array?

前端 未结 10 1078
余生分开走
余生分开走 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:29

    Perhaps to late to the party, but you could just do the following:

    const set = new Set(['a', 'b']);
    const values = set.values();
    const array = Array.from(values);
    

    This should work without problems in browsers that have support for ES6 or if you have a shim that correctly polyfills the above functionality.

    Edit: Today you can just use what @c69 suggests:

    const set = new Set(['a', 'b']);
    const array = [...set]; // or Array.from(set)
    

提交回复
热议问题