集合

這是一種不允許值重復(fù)的順序數(shù)據(jù)結(jié)構(gòu)

描述

  • 集合是由一組無(wú)序且唯一(即不能重復(fù))的項(xiàng)組成的

  • 這個(gè)數(shù)據(jù)結(jié)構(gòu)使用了與有限集合相同的數(shù)學(xué)概念

創(chuàng)建

使用對(duì)象表示集合

class Set {
    constructor() {
        this.items = {}
    }
    /**
     * @description 使用 hasOwnProperty 方法
     * @param {*} value 
     */
    has(value) {
        return this.items.hasOwnProperty(value)
    }
    add(value) {
        if (this.has(value)) {
            return false
        } else {
            this.items[value] = value
            return true
        }
    }
    remove(value) {
        if (!this.has(value)) {
            return false
        } else {
            delete this.items[value]
            return true
        }
    }
    clear() {
        this.items = {}
    }
    size() {
        let count = 0
        for (let key in this.items) {
            if (this.items.hasOwnProperty(key))
                ++count
        }
        return count
    }
    values() {
        let values = []
        
        for (let key in this.items) {
            if (this.items.hasOwnProperty(key)) {
                values.push(this.items[key])
            }
        }
        return values
    }
}

方法的實(shí)現(xiàn)

has(value) 方法

/**
 * @description 使用 hasOwnProperty 方法
 * @param {*} value 
 */
has(value) { 
    return this.items.hasOwnProperty(value)
}

/**
 * @description 使用 in 操作符
 * @param {*} value 
 */
has(value) { 
    return value in this.items
}

size() 方法

// 遍歷對(duì)象的所有屬性
size() {
    let count = 0 
    for (let key in this.items) {
        if (items.hasOwnProperty(key)) // 檢查他們是否是對(duì)象自身的屬性
            ++count
    } 
    return count
}

注意

  • 不能簡(jiǎn)單地使用 for-in 語(yǔ)句遍歷 items 對(duì)象的屬性,并遞增 count 變量的值。還需要使用 hasOwnProperty 方法(以驗(yàn)證 items 對(duì)象具有該屬性),因?yàn)閷?duì)象的原型包含了額外的屬性(屬性既有繼承自 JavaScript 的 Object 類(lèi)的,也有術(shù)語(yǔ)對(duì)象自身,未用于數(shù)據(jù)結(jié)構(gòu))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容