如何实现多层复杂的数据类型的深拷贝
function deepCopy(data) {
if (data.constructor.name === ‘Array’) { // 判断为数组类型
var arrCopy = []
for (var i = 0, len = data.length; i < len; i++) {
//遍历数组
if (data[i] instanceof Object) {// arrary object null以下有关于instanceof的注解
arrCopy.push(deepCopy(data[i]))
} else { // 基本类型
arrCopy.push(data[i])
}
}
return arrCopy;
} else { // 为对象
var objCopy = {};
for (x in data) {
if(data[x] instanceof Object){
objCopy[x] = deepCopy(data[x])
}else{ // 基本类型
objCopy[x] = data[x];
}
}
return objCopy;
}
}
var data = [{
‘list’: [{
name: ‘wh’,
age: 22,
dec:{},
a:[]
},
{
name: ‘hs’,
age: 21
}, {
name: ‘ls’,
age: 23,
}
]
},
{
}]
var res = deepCopy(data)
console.log(res)
javascript 判断该对象是否为数组
1.typeof
使用typeof 可以检测出的基本类型有:Function,String,Number,Undefined;
如代码:
function test(){}
console.log(typeof 22);// number
console.log(typeof test);//function
console.log(typeof “zhangshan”);// string
consle.log(typeof underfined);// underfined
注意:使用typeof判断数据类型时,发现对象,数组, null无法区分准确的类型
console.log(typeof []); object
console.log(typeof /\d+/g);// object
console.log(typeof null === ‘object’)
console.log(typeof [] === ‘object’)
console.log(typeof {} === ‘object’)
2.Instanceof
使用instanceof 来检测某个对象是否是数组,该检测会返回一个布尔型(Boolean),如果是数组的话,返回true,否则的话返回false;例如以下实例:
console.log([] instanceof Array); // true
console.log(/\d+/g instanceof Array); //false
以下代码检测空值Null
console.log([] instanceof Object)//true
console.log({} instanceof Object)//true
console.log(null instanceof Object)//false
console.log(‘sss’ instanceof Object)//false
console.log(true instanceof Object)//false
console.log(123 instanceof Object)//false