两道面试题

 

1.数组去重排序:

  

var arr = [1,1,1,2,2,23,32,78,1,34,221,433];
function arrFoo(arr){
    var arrTemp = [];
    for(var i in arr){
        if(arrTemp.indexOf(arr[i]) === -1){
            arrTemp.push(arr[i]);
        }
    }
    arrTemp.sort(function(a,b){
        return a - b;
    });
    return arrTemp;
}
console.log(arrFoo(arr));

2.深拷贝:

 

var obj = {};
var readycopy = {
    b: {
        c : {
            e : 2
        },
        d : {
            f : 3
        }
    }
};
//Object.assign,new Object, Object.
create都属于浅拷贝,只是对象的引用
function copyIndeep(obj){
    var str;
    if(typeof obj !== "object" || obj === null)
        return;
    var objTemp = obj instanceof Array ? [] : {};
    if(window.JSON){
        str = JSON.stringify(obj);
        objTemp = JSON.parse(str);
        return objTemp;
    }else{
        for(var i in obj){
            if(typeof obj[i] === 'object'){
                objTemp[i] = copyIndeep(obj[i]);
            }else{
                objTemp[i] = obj[i];
            }
        }
        return objTemp;
    }
}
obj.a = copyIndeep(readycopy);
readycopy.b = "123";
console.log(obj);

 

 

  

posted @ 2017-06-29 13:57  danSingle  阅读(352)  评论(0编辑  收藏  举报