美文网首页
使用Array.prototype为数组添加一个去重的方法

使用Array.prototype为数组添加一个去重的方法

作者: 小龙虾Julian | 来源:发表于2020-04-14 10:50 被阅读0次

要求输入一个数组:

var arr = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]

输出:
[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']

注意:NaN === NaN 为false,{} === {}为false

Array.prototype.uniq = function () {
        if (!this.length || this.length == 0) return this;
                var res = [], key, hasNaN = false, temp = {};
        for (var i = 0 ; i < this.length; i++) {
                        if (typeof this[i] === 'object') {
                                res.push(this[i]);
            } else if (this[i] != this[i]) { // 如果当前遍历元素是NaN
                if (!hasNaN) {
                    res.push(this[i]);
                    hasNaN = true;
                }
            } else {
                key = typeof(this[i]) + this[i];
                if (!temp[key]) {
                    res.push(this[i]);
                    temp[key] = true;
                }
            }
        }
        return res;
}   
var arr = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
console.log(arr.uniq())  //[false, true, undefined, null, NaN, 0, 1,{}, {}, "a"]

方法优化:

Array.prototype.uniq = function () {
    var res = [];
    var flag = true;
    this.forEach(function(x) {
        if (res.indexOf(x) == -1) {
            if (x != x) {
                if (flag) {
                    res.push(x);
                    flag = false;
                }
            } else {
                res.push(x);
            }
        }
    })
    return res;
}
var arr = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
console.log(arr.uniq())  //[false, true, undefined, null, NaN, 0, 1,{}, {}, "a"]

相关文章

  • 使用Array.prototype为数组添加一个去重的方法

    要求输入一个数组: 输出:[false, true, undefined, null, NaN, 0, 1, {}...

  • JS中的常用操作

    一、数组去重 常规数组去重一般为双重遍历和使用indexOf方法 1.使用双层for循环去重 2.使用indexO...

  • JS数组去重方式

    1.ES6去重 2.使用indexOf()方法 3.数组forEach方法 4.添加原型方法

  • Array.prototype

    Array.prototype 允许为所有数组对象附加新的方法 本身也是一个Array数组 是Array构造函数的...

  • js中处理数组小技巧

    1、数组去重 1、from()叠加new Set()方法 字符串或数值型数组的去重可以直接使用from方法。 2、...

  • 63、十三个JavaScript数组的方法

    1、数组去重from()叠加new Set()方法。 字符串或数值型数组的去重可以直接使用from方法。 2、sp...

  • WEB 五

    数组中常用的方法 数组中有很多常用的方法 console.dir(Array.prototype)可以看到很多很多...

  • js数组常用方法

    数组常用的方法是指:继承了数组原型(Array.prototype)上的方法 一、push、unshift 增加数...

  • js数组去重

    面试常问数组去重方法有那些: 1.用Es6的Set方法 2.使用双重for循环,再利用数组的splice方法去重(...

  • JS数组去重

    数组去重的方法 1.Set() + Array.from() 2.双层循环 + splice 3.空数组添加 + ...

网友评论

      本文标题:使用Array.prototype为数组添加一个去重的方法

      本文链接:https://www.haomeiwen.com/subject/eclzmhtx.html