JS基础类型
typeof能判断哪些类型
- 识别所有值类型
- 识别函数
- 判断是否是引用类型(不可再细分)
//判断所有值类型
let a; typeof a //'undefined'
let str = 'abc'; typeof str //'string'
let n = 100; typeof n //'number'
let b = true; typeof b //'boolean'
let s = Symbol('s') typeof s //'symbol'
//能判断函数
typeof console.log //'function'
typeof function () {} //'function'
//能识别引用类型(不能再继续识别)
typeof null //'object'
typeof ['a', 'b'] //'object'
typeof { x: 100 } //'object'
何时使用
===
何时使用==
//除了 == null之外.其他一律用 ===,例如:
const obj = {x: 100}
if (obj.a == null) {}
//相当于
// if (obj.a === null || obj.a === undefined) {}
值类型和引用类型的区别
const obj1 = {x: 100, y: 200}
const obj2 = obj1
let x1 = obj1.x
obj2.x = 101
x1 = 102
console.info(obj1) //{x: 101}
手写深拷贝
- 注意判断
值类型
和引用类型
- 注意判断是
数组
还是对象
- 递归
/**
* 深拷贝
* @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
}
变量类型
- 值类型
VS
引用类型
//值类型
let a = 100
let b = a
a = 200
console.info(b) //100
//引用类型
let a = {age: 20}
let b = a
b.age = 21
console.info(a.age)
//常见值类型
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']
const n = null //特殊引用类型,指针指向为空地址
//特殊引用类型,但不用于存储数据,所以没有“拷贝、复制函数”这一说
function fn() {}
typeof
运算符
变量计算 —— 类型转换
- 字符串拼接
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
//除了 == 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.info(10 & 0) //0
console.info('' || 'abc') //'abc'
console.info(!window.abc) //true