小结:
- typeof 运算符
- 类型转换, truly 和 falsely 变量
- 值类型 vs 引用类型,堆栈模型,深拷贝
1. typeof
能判断的类型?
考点:JS变量类型
typeof 运算符
- 识别所有值类型
- 识别函数
- 判断是否是引用类型(不可在细分)
// 判断所有值类型
let a; typeof a // 'undefined'
const str = '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’
typeof function () {} // 'function'
typeof isNaN // 'function'
// 能识别引用类型 (不能再继续识别)
typeof null // 'object'
typeof ['a', 'b' ] // 'object'
typeof { x: 100 } // 'object'
检测数组的几种方式:
Array.isArray([1,2,3]); // true (ES5)
toString.call([]); // "[object Array]"
var arr = [];
arr.constructor; // ƒ Array() { [native code] } 不推荐使用,因为constructor是可以修改的。
[] instanceof Array // true
突然间忘记了!!
浏览器控制台开起来,自行输入,得出答案!!
2. 何时使用 ===
何时使用 ==
考点:强制类型转换
字符串拼接 (只要有字符串,就是字符串拼接)
const a = 100 + 10 // 110
const b = 100 + '10' // '10010'
const c = true + '10' // 'true10'
==
运算符 (隐式类型转换) 如果使用===
, 则全部为false
100 == '100' // true
0 == '' // true
0 == false // true
false == '' // true
null == undefined // true
除了 == null 之外,其他都一律使用 ===
// 除了 == 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
3. 值类型和引用类型的区别
// 值类型
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'
const n = 100
const b = true
const s = Symbol('s')
常见引用类型
const obj = { x:100 }
const arr = ['a', 'b', 'c' ]
const n = null // 特殊引用类型,指针指向为空地址
// 特殊引用类型, 但不用于存储数据,所以没有“拷贝,复制函数” 这一说法
function fn() {}
4. 手写深拷贝
- 注意判断值类型和引用类型
- 注意判断是数组还是对象
- 递归
/**
* 深拷贝
*/
const obj1 = {
age: 20,
name: 'xxx',
address: {
city: 'beijing'
},
arr: ['a', 'b', 'c']
}
const obj2 = deepClone(obj1)
obj2.address.city = 'shanghai'
obj2.arr[0] = 'a1'
console.log(obj1.address.city)
console.log(obj1.arr[0])
/**
* 深拷贝
* @param {Object} obj 要拷贝的对象
*/
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
}
好记性不如多敲敲!!