Js 常见数据类型及判断方法及手写深拷贝

发布时间 2023-05-31 21:49:01作者: playforkeeps

常见 值 类型:undefined、String、Number、boolean、Symbol.

常见 引用类型:Array、Object、function(特殊引用类型,单不用于存储数据,所以  “没有拷贝、复制函数”  这说法)、null(特殊引用类型,指针指向为空地址)

判断数据类型的方法:

  1. typeof 运算符
  2. let a; 
    const string = 'abc';
    const n = 100;
    const b = true;
    const s = Symbol('s');
    
    typeof a; //  'undefined'
    typeof string;  //  'string'
    typeof n; //  'number'
    typeof b; //  'boolean'
    typeof s; //  'symbol'
    typeof function (){}; //  'symbol'
    
    typeof null; //  'object'
    typeof {}; //  'object'
    typeof []; //  'object'

     

  3.  

  4. /**
 * 深拷贝
 * @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 }