前端面试题2--JS基础--变量类型和计算

165 阅读2分钟

1.typeof能判断哪些类型

  • 识别所有值类型
  • 识别函数
  • 判断是否是引用类型(不可再细分)
let a                 typeof a // undefined
const s = 'abc'       typeof s // '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 null         // 'object'
typeof ['a', 'b']   // 'object'
typeof {x: 100}     // 'object'

2.值类型和引用类型的区别

  • 值类型 常见值类型
let a // undefined
const s = 'abc'
const n = 100
const b = true
const s = Symbol('s')
key value
a 100
   
key value
a 100
b 100
  • 引用类型 常见引用类型
const obj = {x: 100}
const arr = ['a', 'b']
const n = null // 特殊引用类型,指针指向为空指针
// 特殊引用类型,但不用于存储数据,所以没有"拷贝、复制函数"这一说
function fn () {}

栈从上往下累加,堆从下往上累加

key value
a 内存地址1
   
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)
/**
* 深拷贝
* @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
}

4.何时使用 === 何时使用 ==

// 除了 == null 之外,其他都一律使用 === ,例如:
const obj = {x: 100}
if (obj.a == null) {}
// 相当于
// if (obj.a === null || obj.a === undefined) ()

5.变量计算-类型转换

  • 字符串拼接
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
例如:
// 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

6.小结

  • 值类型 vs 引用类型,堆栈模型,深拷贝
  • typeof 运算符
  • 类型转换, truly 和 falsely 变量