04-JS基础-变量类型和计算
Question1: 值类型和引用类型的区别
值类型:
//值类型
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
const s = 'abc' //String
const n = 100 //Number
const b = true //Boolean
const s = Symbol('s') //Symbol
// 常见引用类型
const obj = { x: 100 }
const arr = ['a', 'b', 'c']
const n = null // 特殊引用类型,指针指向为空地址
// 特殊引用类型,但不用于存储数据,所以没有拷贝、复制函数这一说
function fn() {}
Question2: typeof 能判断哪些类型
- 识别所有值类型
- 识别函数
- 判断是否是引用类型(不可再细分)
// 能判断所有值类型
let a typeof a // 'undefined'
const s = 'abc' typeof str //'string'
const n = 100 typeof n //'number'
const b = true typeof b //'boolean'
const s = Symbol('s') typeof s //'symbol'
// 能判断函数
typeof console.log // 'function'
type of function () {} // 'function'
// 能识别引用类型(不能再继续识别)
typeof null // 'object'
typeof ['a', 'b'] // 'object'
typeof { x: 100 } // 'object'
Question3: 手写深拷贝
- 注意判断值类型和引用类型
- 注意判断是数组还是对象
- 递归
// 深拷贝
const obj1 = {
age: 20,
name: 'xxx',
address: {
city: 'beijing'
},
arr: ['a', 'b', 'c']
}
const obj2= obj1
obj2.address.city = 'shanghai'
console.log(obj1.address.city) // shanghai, 引用类型的浅拷贝
// 深拷贝
function deepClone(obj = {}) {
if (typeof obj !== 'object' || obj ==null) {
//obj是null或者不是对象和数组,直接返回
return obj
}
// 初始化返回结果
let result
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj) {
// 保证 key不是原型的属性
if (obj.hasOwnProperty(key)) {
// 递归调用!!!,防止有深层次的东西
result[key] = deepClone(obj[key])
}
}
//返回结果
return result
}
const obj3 = deepClone(obj1)
obj3.address.city = 'shanghai'
console.log(obj1.address.city) //beijing
变量计算-类型转换
Question4: 何时使用== 运算符?何时使用===运算符
除了==null之外,其他一律都用三等号
类型转换出现的场景:
-
字符串拼接
-
==
-
if语句和逻辑运算
字符串拼接:
const a = 100 + 10 // 110
const b = 100 + '10' // '10010'
const c = true + '10' // 'true10'
==运算符: ==会隐式的做类型转换
100 == '100' //true
0 == '' //true
0 == false //true
false == '' //true
null == undefined //true
// 上述的几个==变成===一律变成false
// !!!!!除了== null之外,其他一律都用 ===,例如:
const obj = { x: 100 }
if( obj.a == null){}
//相当于:if( obj.a === null || obj.a === undefined){}
if语句和逻辑运算
- truly变量:!!a ===true 的变量
- falsely变量: !!a ===false 的变量
// 以下是falsely变量。除此之外都是truly变量
!!0 === false
!!NaN === false
!!'' === false
!!null === false
!!undefined === false
!!false === false
if语句
// truly 变量
const a = true
if (a) {
// ...
}
const b = 100
if (b) {
// ....
}
// falsely 变量
const c = ''
if (c){
// ....
}
const d = null
if (d){
// ....
}
let e
if (e) {
// ....
}
逻辑判断
console.log(10 && 0) // 0
console.log('' || 'abc') // 'abc'
console.log(!window.abc) // true