1.typeof能判断哪些类型
- 识别所有值类型
- 识别函数
- 判断是否是引用类型(不可再细分)
let a typeof a
const s = 'abc' typeof s
const n = 100 typeof n
const b = true typeof b
const s = Symbol('s') typeof s
typeof console.log
typeof function () {}
typeof null
typeof ['a', 'b']
typeof {x: 100}
2.值类型和引用类型的区别
let a
const s = 'abc'
const n = 100
const b = true
const s = Symbol('s')
const obj = {x: 100}
const arr = ['a', 'b']
const n = null
function fn () {}
栈从上往下累加,堆从下往上累加
| 栈 |
| key |
value |
| a |
内存地址1 |
| b |
内存地址1 |
| 内存地址1 |
{age: 20} |
| key |
value |
| 堆 |
| 内存地址1 |
{age: 20} |
| key |
value |
| 堆 |
3.手写深拷贝
- 注意判断值类型和引用类型
- 注意判断是数组还是对象
- 递归
const obj1 = {
age: 20,
name: 'xxx',
address: {
city: 'beijing'
},
arr: ['a', 'b']
}
const obj2 = deepClone(obj1)
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] = deepClone(obj[key])
}
}
return result
}
4.何时使用 === 何时使用 ==
const obj = {x: 100}
if (obj.a == null) {}
5.变量计算-类型转换
const a = 100 + 10
const b = 100 + '10'
const c = true + '10'
100 == '100'
0 == ''
0 == false
false == ''
null == undefined
const obj = {x: 100}
if (obj.a == null) {}
- if 语句和逻辑判断
truly变量: !!a === true 的变量
falsely变量: !!a === false 的变量
!!0 === false
!!NaN === false
!!'' === false
!!null === false
!!undefined === false
!!false === false
例如:
const a = true
if (a) {
}
const b = 100
if (b) {
}
const c = ''
if (c) {
}
const d = null
if (d) {
}
let e
if (e) {
}
逻辑判断
console.log(10 && 0)
console.log('' || 'abc')
console.log(!window.abc)
6.小结
- 值类型 vs 引用类型,堆栈模型,深拷贝
- typeof 运算符
- 类型转换, truly 和 falsely 变量