Set知識點和手寫模擬Set對象

Set對象

Set對象用於存儲任何類型的唯一值。

const s1 = new Set([1, 2, 3, 3, '3'])
console.log(s1)

// Set(4) {1, 2, 3, "3"}
// [[Entries]]
// 0: 1
// 1: 2
// 2: 3
// 3: "3"
// size: 4
// __proto__: Set

size記錄着Set對象的長度。

console.log(s1.size)

// 4

遇見字符串時會轉換爲字符串對象在進行儲存

const s1 = new Set('Hello world')
console.log(s1)

// Set(8) {"H", "e", "l", "o", " ", "w", "r", "d"}
實例方法

add(key) 添加key值在Set對象中。

const s1 = new Set();
s1.add(1)
s1.add(2)
s1.add(3)
s1.add(3)
console.log(s1)

// Set(3) {1, 2, 3}
  • Set對象認爲 +0-0 是相同的,所以同時添加 +0-0 顯示一個 0

delete(key) 刪除Set對象中的key值,返回是否刪除成功。

console.log(s1.delete(1))
console.log(s1)

// true
// Set(2) {2, 3}

has(key) 判斷Set對象中是否存在key值。

console.log(s1.has(1))
console.log(s1.has(10))

// true
// false

clear() 清空當前Set對象的值。

s1.clear()
console.log(s1)

// Set(0) {}

forEach()forEach()的重寫

s1.forEach((item, index, s) => {
    // forEach中的第一個參數的值和第二個參數的值是相同的,都表示set中的每一項
    console.log(item, index, s)
})

// 1 1 Set(4) {1, 2, 3, 4}
// 2 2 Set(4) {1, 2, 3, 4}
// 3 3 Set(4) {1, 2, 3, 4}
// 4 4 Set(4) {1, 2, 3, 4}

利用Set對象數組去重

var arr = [1, 2, 3, 4, 5, 5, 2, 2, 1, 3, 34, 42, 3, 1, 3, 1]
var newarr = [...new Set(arr)]
console.log(newarr)

// [1, 2, 3, 4, 5, 34, 42]

利用Set對象字符串去重

const str = "hello world";
const s = [...new Set(str)].join("")
console.log(s)

// helo wrd

手寫模擬Myset對象

class MySet {
    constructor(iterator) {
        // 判斷iterator是否是一個可迭代對象
        if (typeof iterator[Symbol.iterator] !== 'function') {
            throw new TypeError(`你提供的${iterator}不是一個可迭代對象`)
        }
        this._datas = [];
        for (const item of iterator) {
            this.add(item)
        }
    }

    get size() {
        return this._datas.length
    }

    add(data) {
        if (!this.has(data)) {
            this._datas.push(data)
        }
    }

    has(data) {
        for (const item of this._datas) {
            if (this.isEqual(data, item)) {
                return true;
            }
        }
    }

    delete(data) {
        for (let i = 0; i < this._datas.length; i++) {
            if (this.isEqual(data, this._datas[i])) {
                this._datas.splice(i, 1)
                return true;
            }
        }
        return false;
    }

    clear() {
        this._datas.length = 0;
    }

    forEach(callback) {
        for (let item of this._datas) {
            callback(item, item, this)
        }
    }

    isEqual(data1, data2) {
        // 判斷+0和-0爲相等
        if (data1 === 0 && data2 === 0) {
            return true
        }
        return Object.is(data1, data2)
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章