[JavaScript初级面试]2. JS基础-变量类型和计算

题目

  1. typeof能判断哪些类型
  2. 何时使用 === 何时使用 ==
  3. 值类型和引用类型的区别
  4. 如何实现深拷贝

值类型和引用类型

示例

// 值类型
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

值类型在栈中存储:
image
引用类型在堆中存储:(为了节省内存,复用数据)
image

常见值类型

let a // undefined
const s = 'abc'
const n = 1000
const b = true
const s = Symbol('s')

常见引用类型

cosnt obj = { x : 100 }
const arr = [1, 2, 3]
const n = null //特殊引用类型,指针指向空地址
function fn(){} //特殊引用类型,不用于存储数据,没有拷贝,复制的问题

typeof

可以识别出所有的值类型

let a 				typeof a// undefined
const s = 'abc'			typeof s // string
const n = 1000			typeof n // number
const b = true			typeof b // boolean
const s = Symbol('s')		typeof s // symbol

可以识别函数

typeof console.log	// function
typeof function(){}	// function

可以判断是否是引用类型(Object)不可再细分

typeof null		// object
typeof [1,2]		// object
typeof {x:100}		// object

深拷贝(引用类型的复制)

// 前提:对象内的属性,只能是值类型,function,Array
// 普通Object(非Map,Set等其他特殊对象)
// for-in 无法遍历Map,Set等
// JSON.stringfy会丢失Map,Set内部信息,只返回一个空{}
function deepClone(obj = {}){
  if(typeof obj !== 'object' || obj == null){
    return obj // 如果是值类型,function,null直接返回
  }
  let result
  if(obj instanceof Array)
    result = []
  } else {
    result = {}
  }
  for(let key in obj){ // for-of 循环只能遍历iterable
    if(obj.hasOwnProperty(key)){ // 保证key不是当前对象原型链上的属性
      result[key] = deepClone(obj[key]) // 递归调用
    }
  }
  return result
}

类型转换

可能发生类型转换的场景:

1.字符串拼接

const a = 100 + 10 // 110
const b = 100 + '10' // '10010'
const c = true + '10' // 'true10'

使用parseInt or ParseFloat可以把变量转为相应的数字

2.==

100 == '100' // true
0 == '' // true
0 == false // true
null == undefined // true

== 会尽量转换两侧的操作数,让他们转换为最可能相等的类型,从而趋向于相等
除了判断一个变量 == null 之外,其余一律用 ===
obj == null 等同于 obj === null || obj === undefined

3.if语句

  • falsely变量:!!a === false
!!0 === false
!!NaN === false
!!'' === false
!!null === false
!!undefined === false
!!false === false
  • truely变量:!!a === true
    除了上面的falsly变量外,都是truely变量
if(变量){
  // 当变量是truely变量时,执行
}else{
  // 当变量是falsly变量时,执行
}

4.逻辑运算

// 与 运算,如果有一个为false,则返回它;
// 如果没有一个false,则返回第一个为true的
0 && 10 => 0
10 && 0 => 10
// 或 运算,只返回(或执行)可以转化为true的表达式,变量,函数,对象等
0 || 10 => 10
10 || 0 => 10
posted @ 2021-09-02 10:20  Max力出奇迹  阅读(39)  评论(0编辑  收藏  举报
返回顶部↑