Set

2017-07-26  本文已影响0人  老虎爱吃母鸡

使用Set对JSON进行去重

其实本质是对字符串去重,但是可以扩展开对Set的理解和使用

define

The Set object lets you store unique values of any type, whether primitive values or object references.

Set是对象不是数组,可以用来储存任何类型的独特的值,不管是原始类型还是引用类型

signature

new Set([iterable])

Parameters

If an iterable object is passed, all of its elements will be added to the new Set. If you don't specify this parameter, or its value is null, the new Set is empty.

Set接受的参数是布置了遍历器接口的数据结构,然后会把它的元素都添加到Set中,如果你没有指定参数,或者参数的值是null,那么新构造的Set会是空的

Description

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.

Set对象是值的集合,你可以按照插入Set的顺序遍历元素,一个值在Set中只能发生一次

Value equality

Because each value in the Set has to be unique, the value equality will be checked. In an earlier version of ECMAScript specification this was not based on the same algorithm as the one used in the === operator. Specifically, for Sets, +0 (which is strictly equal to -0) and -0 were different values. However, this was changed in the ECMAScript 2015 specification. See "Value equality for -0 and 0" in the browser compatibility table for details.

Also, NaN and undefined can also be stored in a Set. NaN is considered the same as NaN (even though NaN !== NaN).

not based on the same algorithm as the one used in the === operator
不是基于全等操作符中使用的相同的算法

Set与数组之间的转换

const mySet = new Set([1,2,3,4])
// to Array
[...mySet]
Array.from(mySet)

trick

// 交集
new Set([...set1].filter(x => set2.has(x)))
// 差集
new Set([...set1].filter(x => !set2.has(x)))

reference

Set - MDN

上一篇下一篇

猜你喜欢

热点阅读