飛揚世紀網(wǎng)站建設站長工具查詢網(wǎng)站
我們知道Set是JS的一個種新的數(shù)據(jù)結構,和數(shù)組類似,和數(shù)組不同的是它可以去重,比如存入兩個1或兩個"123",只有1條數(shù)據(jù)會存入成功,但有個特殊情況,如果添加到set的值是引用類型,比如數(shù)組、對象,他將無法自動去重。因為值相同的兩個引用類型地址是不一樣的。下面來看一個例子:
var mySet = new Set()
mySet.add([-1,0,1])
mySet.add([-1,0,1])
mySet.add({a: 1})
mySet.add({a: 1})
mySet.size // 4
console.log(Array.from(mySet)) // [[-1, 0, 1], [-1, 0, 1], {a: 1}, {a: 1}]
我們來看看mdn上的文檔描述:
Set - JavaScript | MDNThe Set object lets you store unique values of any type, whether primitive values or object references.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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.
集合對象是值的集合。您可以按插入順序遍歷集合的元素。集合中的值只能出現(xiàn)一次;它在集合集合中是唯一的。
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 "Key equality for -0 and 0" in the browser compatibility table for details. NaN and undefined can also be stored in a Set. All NaN values are equated (i.e. NaN is considered the same as NaN, even though NaN !== NaN).
由于集合中的每個值都必須是唯一的,因此將檢查值是否相等。在早期版本的ECMAScript規(guī)范中,這與==運算符中使用的算法不同。具體來說,對于集,+0(嚴格等于-0)和-0是不同的值。然而,這在ECMAScript 2015規(guī)范中有所更改。有關詳細信息,請參閱瀏覽器兼容性表中的“-0和0的密鑰相等”。NaN和undefined也可以存儲在Set中。所有NaN值都相等(即,NaN被認為與NaN相同,即使NaN!==NaN)。
我們可以簡單理解為,像Set實例add數(shù)據(jù)時,每次都會進行等值判斷,類似于將add的元素與每個元素進行 === 比較。因此對引用類型的去重是無效的
var stra = "test"
var strb = "test"
var a = { a : 1}
var b = { a : 1}
stra === strb // true
a === b // false 盡管他們都是對象 { a: 1 },但他們存儲的地址是不一樣的
那這種情況怎么去重呢。我們可以自己寫方法來處理,以數(shù)組為例子,可以將值[-1, 0, 1].join('|') 處理下,添加進去,到時統(tǒng)一再split出來
?