在ECMAscript中变量可以存在两种类型的值,分别为基本类型和引用类型。
值类型(基本类型):
Number,String,Boolean,Null,Undefine
在内存中占据固定的大小空间,用栈进行存储。
复制值过程
let num1 = 100;
let num2 = num1;
引用类型:
Object,Function,Array,Date,RegExp
占据大小空间不固定,用堆进行存储。
复制值的过程
let obj1 = {name:"ace"}
let obj2 = obj1;
obj2.name = "bob";
console.log(obj1.name) //bob
类型判断:
使用typeof区分值类型
typeof 100 //number
typeof "ace" //string
typeof a //undefine
typeof true //boolean
typeof undefine //undefine
typeof null //object 历史残留问题
typeof [] //object
typeof function(){} //function
typeof {} //object
使用instanceof 区分引用类型(根据原型链)
[] instanceof Array //true
const obj = {}
obj instanceof Object //true
深拷贝
function deepClone(obj={}){
if(typeof obj!="object" || obj == null){
return obj;
}
let result;
//首先区分是数组还是对象
if(obj instanceof Array){
result = [];
}else{
result = {};
}
for(let key in obj){
if(obj.hasOwnProperty(key)){
result = deepClone(obj[key]);
}
}
return result;
}