变量类型和计算
值类型:
let a = 100;
let b = a;
a = 200;
console.log(b) //100
引用类型
let a = {age:20};
let b = a;
b.age = 21
console.log(a.age) //21
常见值类型
let a //undefined
let s = 'abc';
let n = 100;
let b = true;
let s = Symbol('s');
常见引用类型
let obj = {x:100};
let arr = ['a','b','c'];
let n = null; //特殊引用类型,指针指向为空地址
//特殊引用类型,但不用于存储数据,所以没有“拷贝、复制函数”这一说
function fn() {}
typeof运算符
// 判断所有值类型
let a; typeof a //'undefined'
let str = 'abc'; typeof str //'string'
let n = 100; typeof n //'number'
let b = true typeof n //'boolean'
let s = Symbol('') typeof s //'symbol'
typeof console.log //'function'
typeof function () //'function'
// 能识别引用类型 (不能在继续识别)
typeof null // 'object'
typeof ['a','b'] // 'object'
typeof {x:100} // 'object'
深拷贝
const obj1 = {
age: 20,
name: 'xxxx',
address: {
city: 'beijing'
},
arr: ['a', 'b', 'c']
}
let obj2 = obj1
obj2.address.city = 'shanghai'
console.log(obj1.address.city)
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[key] = deepCopy(obj[key])
}
}
return result
}
变量计算-类型转换
字符串拼接
let a = 100 + 10 //100
let b = 100 + '10' //'10010'
let c = true + '10' // 'true10'
==运算符
100 == '100' //true
0 == '' // true
0 == false // true
false == '' // true
null == undefined // true
//除了 == null 之外,其他都一律用===,例如:
let obj = {x:100}
if(obj.a == null){}
//相当于:
//if(obj.a === null || obj.a === undefined){}