亲宝软件园·资讯

展开

比较新旧两个数组值得增加和删除的JS代码

人气:0

复制代码 代码如下:

  以前项目中用到自己写的,应该没有bug吧,有更好的也欢迎大家指教,
var Return_AddStrFn=function (oldArr, newArr) {
        var t = this;
       //去重复的方法
        Array.prototype.unique4 = function () {
            // this = arr;
            var temp = new Array();
            this.sort();
            for (i = 0; i < this.length; i++) {
                if (this[i] == this[i + 1]) {
                    continue;
                }
                temp[temp.length] = this[i];
            }
            return temp;
        }
        var a = d = oldArr.unique4(); //旧数组
        var b = e = newArr.unique4();//新数组
        var c = [];
        var dels = [];
        function f() {
            a.sort();
            b.sort();
            var i = 0;
            var j = 0;
            while (i < a.length && j < b.length) {
                if (a[i] < b[j]) {
                    c.push(a[i]);
                    i++;
                } else if (b[j] < a[i]) {
                    c.push(b[j]);
                    j++;
                } else {
                    i++;
                    j++;
                }
            }
            while (i < a.length) {
                c.push(a[i]);
                i++;
            }
            while (j < b.length) {
                c.push(b[j]);
                j++;
            }
        }
        f();
        //alert("c:" + c);
        //alert("d:" + d);
        var addstr = [];
        for (var i = 0; i < c.length; i++) {
            for (var j = 0; j < e.length; j++) {
                if (e[j] == c[i]) {
                    addstr.push(e[j]);
                }
            }
        }
        return addstr; //新增的
        //for (var i = 0; i < c.length; i++) {
        //    for (var j = 0; j < d.length; j++) {
        //        if (d[j] == c[i]) {
        //            dels.push(d[j]);
        //        }
        //    }
        //}
        //alert("dels:" + dels); //删除的
    }

调用方式: var arr = [1, 2,2,3, 3, 4, 5];
              var arr2=[1,2,5]

       var addStr=Return_AddStrFn(arr2,arr);

加载全部内容

相关教程
猜你喜欢
用户评论