变量类型和计算
- typeof能判断哪些类型
- 何时使用
===
何时使用==
- 值类型和引用类型的区别
- 手写深拷贝
知识点
- 值类型vs引用类型
- typeof运算符
- 深拷贝
值类型和引用类型
一般来说,值类型的变量值存储在栈内存中,引用类型存储在堆内存中;对于变量来说,引用类型的变量存储的是内存地址。可以这么理解:值类型所占的内存都很少,所以直接存的值,而引用类型可能非常大,计算机查找起来耗时,所以存储的是内存地址,而真正的值存在内存中某一地址块内。
常见值类型
常见值类型symbol、undefined、string、number、boolean、bigint,常见引用类型object(null指向的是空地址)、function(特殊的引用类型)
typeof运算符
typeof运算符能识别所有值类型、函数,判断是否是引用类型(不可再细分)
深拷贝
var obj = {
age: 20,
name: 'ainuo5213',
address: {
city: '北京',
},
arr: ['a', 'b', { thumble: ['a', 'b'] }]
};
function clone(source, isDeepClone) {
isDeepClone = isDeepClone || true;
if(typeof source !== 'object' || source == null) {
return source
}
var target = isObject(source) ? {} : [];
if (isDeepClone) {
for (var key in source) {
var _tempSource = source[key];
if (source.hasOwnProperty(key)) {
if (typeof _tempSource !== 'object' || _tempSource == null) {
target[key] = _tempSource;
} else if (isArray(_tempSource)) {
target[key] = clone(_tempSource, true);
} else if (isObject(_tempSource)) {
target[key] = clone(_tempSource, true);
}
}
}
return target
} else {
return target
}
}
function isObject(obj){
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isArray(arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
}
var clonedObj = clone(obj);
obj.name = 'ainuo5214';
console.log(clonedObj); // ainuo5213
类型转换
- 显示类型转换
显示类型转换即通过特定方法进行的转换,如Number()、String()、toString()等。 - 隐式类型转换
隐式类型转换即不使用显示类型转换的方式进行变量类型转换,如四则运算符、逻辑判断等
==
运算符适用于判断对象中某个属性是否存在,如: obj.xx == null