js 實現去重

 

ES6 set去重this

Array.from(new Set([1,2,3,3,4,4]))    // [1,2,3,4]

[...new Set([1,2,3,3,4,4])]        // [1,2,3,4]

 

使用 for of 去重(On)spa

Array.prototype.distinct = function() {
    const map = {}
    const result = []
    for (const n of this) {
        if (!(n in map)) {
            map[n] = 1
            result.push(n)
        }
    }
    return result
}
[1,2,3,3,4,4].distinct(); //[1,2,3,4]
相關文章
相關標籤/搜索