數(shù)據(jù)結(jié)構(gòu)與算法JavaScript描述(5) —— 字典(Dictionary)

字典

一種以key-value形式存儲數(shù)據(jù)的數(shù)據(jù)結(jié)構(gòu)。

實(shí)現(xiàn):

class Dictionary {

    constructor() {
        this.elements = []
    }

    // 字典中元素個數(shù)
    get length() {
        return Object.keys(this.elements).length
    }

    // 查找元素
    find(key) {
        return this.elements[key]
    }

    // 添加元素
    add(key, val) {
        this.elements[key] = val
    }

    // 移除元素
    remove(key) {
        delete this.elements[key]
    }

    // 清空字典
    clear() {
        this.elements = []
    }

    // 展示字典中的所有鍵值對
    display() {
        // 按字典順序顯示所有元素
    for (let key of Object.keys(this.elements).sort()) {
        console.log(key + ' -> ' + this.elements[key])
    }
    }
}

示例:按字母順序顯示來一段文本中各個單詞出現(xiàn)的次數(shù)

function wordCount(s) {
    const words = s.split(' ')
    var d = new Dictionary()
    words.forEach(item => {
        if (d.find(item)) {
            d.add(item, d.find(item) + 1)
        } else {
            d.add(item, 1)
        }
    })
    d.display()
}

// test
wordCount('the brown fox jumped over the blue fox') // blue -> 1 brown -> 1 fox -> 2 jumped -> 1 over -> 1 the -> 2

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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