4 - JS值类型和引用类型的区别

169 阅读2分钟
  • typeof能判断哪些类型
  • 何时使用=== 何时使用==
  • 值类型和引用类型的区别
  • 手写深拷贝

知识点:

  • 值类型vs引用类型
  • typeof运算符
  • 深拷贝

值类型vs引用类型

值类型

//值类型
let a = 100
let b = a
a = 200 
console.log(b) //100

image.png

常见值类型

let a; //undefined
const str = 'abc'
const n = 100
const b = true
const s = Symbol('s')

引用类型

//引用类型
let a = {age:20}
let b = a
b.age = 21
console.log(a.age) //21

image.png

常见引用类型

const obj = {x:100}
const arr = ['a','b','c']

const n = null //特殊引用类型,指针指向为空地址

//特殊引用类型,但不用于存储数据,所以没有“拷贝、复制函数”这一说法
function fn(){}

值类型和引用类型的区别考题:

const obj1 = {x:100,y:200};
const obj2 = obj1;
let x1 = obj1.x;
obj2.x = 101;
x1 = 102;
console.log(obj1)  //答案{x:101,y:200}

typeof运算符

  • 识别所有值类型
  • 识别函数
  • 判断是否是引用类型(不可再细分)

let a; //undefined
const str = 'abc'
const n = 100
const b = true
const s = Symbol('s')

typeof a; //"undefined"
typeof str;//"string"
typeof n; //"number"
typeof b; //"boolean"
typeof s; //"symbol"


typeof console.log // "function"
typeof function(){} //"function"
 //能识别引用类型但不能再细分
 typeof null //"object"
 typeof ['a','b'] //"object"
 typeof {x:100} //"object"

手写深拷贝

题目如下,实现deepClone深拷贝函数

/*深拷贝*/
const obj1 = {
    age:20,
    name:'tanwa',
    address:{
        city:'Shengzhen'
    },
    arr:['a','b','c']
}

const obj2 = deepClone(obj1);

obj2.address.city = 'Guangzhou';
console.log(obj1.address.city);

/**
 *深拷贝
 *@param {Object} obj 要拷贝的对象
 */
 function deepClone(obj = {}){
     return {}
 }

解答:

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;
}

变量计算 - 类型转换

  • 字符串拼接
  • ==
  • if语句和逻辑运算

字符串拼接

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语句

if语句中,就是通过判断是否是truly变量或falsely变量

//truly变量
const a = true;
if(a){ 
    //...
}
const b = 100;
if(b){
    //...
}

//flasely变量
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