关于javascript:前端js数组对象去重方法

数组对象去重

题目:

// 输出
[false, true, 1, 2, '1', '2', {}, {}, NaN, NaN, undefined, null].uniq();
// 取得
[false, true, 1, 2, '1', '2', {}, {}, NaN, undefined, null]

解决办法:

办法1:

Array.prototype.uniq = function () {
    // 先排除不符合条件
    if (!this.length || this.length == 0) return this;
    let arr = [], hasNaN = false, key, temp = {}, length = this.length;
    for (let i = 0; i<length; i++) {
        if (typeof this[i] == 'object') {
            // 对象间接放进去,因为引入类型指向堆栈不同
            arr.push(this[i])
        } else if (this[i] != this[i]) {
            // 此处判断是否是NaN,并且NaN未放入
            // NaN原型为Number,指的是非数字,所以NaN == NaN返回的是false,因为两个都是非数字,但不能说它们就相等,也可能一个是字符串,一个是数组呢
            if (!hasNaN) {
                // 此处必须把hasNaN的校验放到外面来,不然会的话,会NaN的校验在第二个if条件不合乎后会进入第三个,从而呈现多个NaN
                arr.push(this[i]);
                hasNaN = true;
            }
        } else {
            // 其余类型
            // 进行鉴重校验,如果temp中不存在该key,则放入arr
            // key为类型加值自身,避免数字和字符串的反复
            key = typeof(this[i]) + this[i];
            if (!temp[key]) {
                arr.push(this[i]);
                temp[key] = true;
            }
        }
    }
    return arr;
}

办法2:

办法2区别与办法1在于应用Map来过滤反复。

// 输出
[false, true, 1, 2, '1', '2', {}, {}, NaN, NaN, undefined, null].uniq();
// 取得
[false, true, 1, 2, '1', '2', {}, {}, NaN, undefined, null]

Array.prototype.uniq = function () {
    // 先排除不符合条件
    if (!this.length || this.length == 0) return this;
    let arr = [], hasNaN = false, map = new Map(), length = this.length;
    for (let i = 0; i<length; i++) {
        if (typeof this[i] == 'object') {
            // 对象间接放进去,因为引入类型指向堆栈不同
            arr.push(this[i])
        } else if (this[i] != this[i]) {
            // 此处判断是否是NaN,并且NaN未放入
            // NaN原型为Number,指的是非数字,所以NaN == NaN返回的是false,因为两个都是非数字,但不能说它们就相等,也可能一个是字符串,一个是数组呢
            if (!hasNaN) {
                // 此处必须把hasNaN的校验放到外面来,不然会的话,会NaN的校验在第二个if条件不合乎后会进入第三个,从而呈现多个NaN
                arr.push(this[i]);
                hasNaN = true;
            }
        } else {
            // 其余类型
            // Map能够寄存键值对汇合,且键不仅限于字符串,能够是任何类型,比起办法1省去了key值的构建
            key = this[i];
            if (!map.get(key)) {
                arr.push(this[i]);
                map.set(key, true)
            }
        }
    }
    return arr;
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理