前端面试知识整理——JS基础变量类型和计算
题目
- typedof 能判断哪些类型
- 何时使用 == 和 ===
- 值类型和引用类型的区别
- 手写深拷贝
1 值类型和引用类型
值类型
原因:栈存储 栈中存储的就是值
//值类型
let a = 100
let b = a
a = 200
console.log(b)//100
引用类型
原因:栈和堆同时存储,栈中存储的是内存地址
本质:复杂数据类型可能较大,不方便在栈中存储
//引用类型
let a = { age: 20 }
let b = a
a.age = 21
console.log(b.age) //21
常见值类型
// 常见值类型
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 (){}
2 typedof运算符
- 识别所有值类型
- 识别函数
- 判断是否为引用类型(不可再细分)
//判断所有值类型
let a
console.log(typeof a) //undefined
const str = 'abc'
console.log(typeof str) //string
const num = 123
console.log(typeof num) //number
const flag = true
console.log(typeof flag)// boolean
const s = Symbol('s')
console.log(typeof s) // symbol
//能判断函数
console.log(typeof console.log) //function
console.log(typeof function () {}) //function
//能识别引用类型(不可再细分)
console.log(typeof null) //object
console.log(typeof [1, 2, 3]) //object
console.log(typeof { a: 1 }) //object
3 深拷贝
const obj1 = {
age: 20,
name: 'xxx',
address: {
city: 'beijing',
},
arr: ['a', 'b', 'c'],
}
//浅拷贝
const obj2 = obj1
obj2.address.city = 'shanghai'
//修改obj2的值时,obj1也会改变,要避免这种现象
console.log(obj1.address.city) //shanghai
const obj1 = {
age: 20,
name: 'xxx',
address: {
city: 'beijing',
},
arr: ['a', 'b', 'c'],
}
const obj2 = deepClone(obj1)
obj2.address.city = 'shanghai'
console.log(obj1.address.city) //beijing
//深拷贝函数
function deepClone(obj) {
//当前obj不是对象或者数组,或者为null时直接返回原来的值
if (typeof obj != 'object' || obj == null) {
return obj
}
//初始化返回结果
let res
if (obj instanceof Array) {
res = []
} else {
res = {}
}
for (let key in obj) {
// 保证 key 不是原型的属性
if (obj.hasOwnProperty(key)) {
// 递归调用
res[key] = deepClone(obj[key])
}
}
return res
}
4 变量计算—类型转换
- 字符串拼接
- ==
- if语句和逻辑运算
const a = 100 + 10 //110
const b = 100 + '10' //10010
const c = true + '10' //true10
//以下结果都为 true
100 == '100'
0 == ''
0 == false
false == ''
null == undefined
//结论:判断时除了 == null之外,其他都一律用 ===
//js中判断的是truly变量而不是true或者false
//truly变量:!!a === true 的变量
//falsely变量:!!a === false 的变量