JS数组去重和取重

本文介绍了一种使用JavaScript自定义方法实现数组去重和提取重复元素的技术。通过修改数组原型,提供了两种方法,一种用于去除数组中的重复元素,另一种用于获取数组中的重复项。示例代码展示了如何应用这些方法。
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS数组去重和取重</title>
</head>

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>

<body>
</body>
<script>
    Array.prototype.distinct = function () {
        var a = [], b = [];
        for (var prop in this) {
            var d = this[prop];
            if (d === a[prop]) continue; //防止循环到prototype
            if (b[d] != 1) {
                a.push(d);
                b[d] = 1;
            }
        }
        return a;
    }
    var x = [1,1,2,2,3,4,4,5];
    document.write('原始数组:' + x);
    document.write("<br />");
    document.write('去重复后:' + x.distinct());
    document.write("<br />");
</script>
方法二:取重复数据
<script type="text/javascript">
    Array.prototype.distinct = function () {
        var a = [], b = [], c = [], d = [];
        for (var prop in this) {
            var d = this[prop];
            if (d === a[prop]) {
                continue;
            }//防止循环到prototype
            if (b[d] != 1) {
                a.push(d);
                b[d] = 1;
            }
            else {
                c.push(d);
                d[d] = 1;
            }
        }
//return a;
        return c.distinct1();
    }
    Array.prototype.distinct1 = function () {
        var a = [], b = [];
        for (var prop in this) {
            var d = this[prop];
            if (d === a[prop]) continue; //防止循环到prototype
            if (b[d] != 1) {
                a.push(d);
                b[d] = 1;
            }
        }
        return a;
    }
    var x = [1,1,2,2,3,4,4,5];
    document.write("<br />");
    document.write('原始数组:' + x);
    document.write("<br />");
    document.write('去重复后:' + x.distinct());
</script>
</html>

 

转载于:https://www.cnblogs.com/tytsp/p/9687322.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值