在javascipt中,有array数组对象,object对象,正则对象,函数对象,typeof只能判断是对象,但是却不能判断属于何种对象。
记录一个方法用来判断对象属于那种对象:
使用Object.prototype.toString.call(elem).toLowerCase() 获取对象的类型,再使用 == 来判断是否该类型的对象。
看下图,对象是引用类型的值,所以当赋值一个对象的时候,不能象普通类型一样赋值,因为在引用类型赋值后,修改对象的值会直接修改到引用类型中的值,所以,赋值一个对象的时候,如果后面修改了对象的值,赋予过该对象的变量都会被修改。
所以,拷贝数据的时候,需要深拷贝:
//判断一个是不是JSON对象,1.对象是没长度的,2.类型是对象3.判断是对象的那个类型:object,object
function isJSON(elem){
console.log(typeof elem);
console.log(!elem.length);
console.log(Object.prototype.toString.call(elem)==='[object object]');
return typeof elem === "object" && !elem.length && Object.prototype.toString.call(elem).toLowerCase()=="[object object]";
}
//判断是不是数组
function isArray(elem){
if(Array.isArray){
return Object.prototype.toString.call(elem).toLowerCase() == '[object array]';
}else{
console.log(1);
return Array.isArray(elem);
}
}
function isSimpleType(elem){
return typeof elem === "string" || typeof elem === 'number'|| typeof elem === 'boolean';
}
function deepCopyJSON(json){
if(!isJSON(json)){return ;}
var newJSON = {};
for(var key in json){
if(isJSON(json[key])){
newJSON[key] = deepCopyJson(json[key])
}else if(isArray(json[key])){
newJSON[key] = deepCopyArray(json[key])
}else{
newJSON[key] = json[key];
}
}
return newJSON;
}
function deepCopyArray(arr){
if(!isArray(arr)){return ;}
var newArr = [];
console.log('isArr');
for(var i=0;i<arr.length;i++){
if(isJSON(arr[i])){
// console.log(0);
newArr[i] = deepCopyJSON(arr[i]);
}else if(isArray(arr[i])){
newArr[i] = deepCopyArray(arr[i]);
}else{
console.log(0);
newArr[i] = arr[i];
}
}
return newArr;
}
function deepCopy(obj){
var newObj;
if(isArray(obj)){
newObj = deepCopyArray(obj);
}else if(isJSON(obj)){
newObj = deepCopyJson(obj);
}
return newObj;
}
var json1 = {
'a':1,
'b':'string',
'c':true,
'd':{
'a':11,
'b':true,
'c':{
'aa':false,
'bb':'字符'
}
},
'e':[1,4,5,{a:'555','b':'hahahah'}]
};
var arr1 = [1,4,'dddd',{'a':'a','b':'b'},[11,33,44,55,{'t':'t','y':'y'}]];
var arr2=deepCopyArray(arr1);
//arr2[4][4].t=3;
//arr1[4][4].1 输出t