1、深度克隆
    var newObj ={};
    function deepClone(origin,target){
        var target = target || {},
        toStr = Object.prototype.toString,
        arrStr = "[object Array]";

        for(var propin origin){
            if(origin.hasOwnProperty(prop)){
                if(origin[prop] != "null" && typeof(origin[prop]) == 'object'){//判斷原型鏈
                    target[prop] = (toStr.call(origin[prop]) == arrStr) ? [] : {}//判斷obj的key是否是數組
                    deepClone(origin[prop],target[prop]);//遞歸的方式
                }else{
                    target[prop] = origin[prop];
                }
            }
        }
        return target
    }

    deepClone(obj,newObj);
    console.log(newObj)

2、求數組最大值和最小值


Array.prototype.max = function(){
return Math.max.apply({},this)
}

Array.prototype.min = function(){
return Math.min.apply({},this)
}

console.log([1,5,2].max())


3、json數組去重


function UniquePay(paylist){
var payArr = [paylist[0]];
for(var i =1; i < paylist.length; i++){
var payItem = paylist[i];
var repeat = false;
for (var j =0; j < payArr.length; j++) {
if (payItem.name == payArr[j].name) {
repeat = true;
break;
}
}
if (!repeat) {
payArr.push(payItem);
}
}
return payArr;
}
4、對比兩個數組,取出交集


Array.intersect = function () {
var result = new Array();
var obj = {};
for (var i =0; i < arguments.length; i++) {
for (var j =0; j < arguments[i].length; j++) {
var str = arguments[i][j];
if (!obj[str]) {
obj[str] = 1;
}
else {
obj[str]++;
if (obj[str] == arguments.length)
{
result.push(str);
}
}//end else
}//end for j
}//end for i
return result;
}
console.log(Array.intersect(["1","2", "3"], ["2","3", "4", "5", "6"]))


5、數組和對象比較。取出對象的key和數組元素相同的


var arr = ['F00006','F00007','F00008'];
var obj = {'F00006':[{'id':21}],'F00007':[{'id':11}]}
var newobj = {};
for(var itemin obj){
if(arr.includes(item)){
newobj[item] = obj[item]
}
}
console.log(newObj)

6、刪除數組中某個元素


//第一種
Array.prototype.remove = function(val){
var index = this.indexOf(val);
if(index !=0){
this.splice(index,1)
}
}
[1,3,4].remove(3)
//第二種
function remove(arr, indx) {
for (var i =0; i < arr.length; i++) {
var index = arr.indexOf(arr[i]);
if (indx == index) {
arr.splice(index, 1)
}
}
return arr
}

7、判斷數組是否包含某個元素


Array.prototype.contains = function (val) {
for (var i =0; i < this.length; i++) {
if (this[i] == val) {
return true;
}
}
return false;
};

[1, 2,3, 4].contains(2)//true

  哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業制作大氣、美觀的優秀網站,并且能夠搭建符合百度排名規范的網站基底,使您的網站無需額外費用,即可穩步提升排名至首頁。歡迎體驗最佳的哈爾濱網站建設。