JS-数据类型

55 阅读1分钟

一、数据类型:

1、基础类型:5个

1String
2Number
3Boolean
4) Undefind
5)new Symbol()
6)null

2、引用类型:

1) Array
2) Obiect
3) function
4) new Date()

3.特殊的引用类型:

2) null:
2) function

二、判断数据类型:

1、typeof 方法, 1)用来准确判断基本类型(除了null)

1)typeof null //'object'
  1. typeof 不能准确的判断引用类型
eg:
2)typeof function(){}  //'function'
3)typeof []   //'object'
4)typeof ()   //'object'
5)typeof new Date()  //'object'

2、Object.prototype.toString (全能选手

var toString=Object.prototype.toString; 

console.log(toString.call(undefined)); // [object Undefined] 
console.log(toString.call(null)); // [object Null] 
console.log(toString.call(false)); // [object Boolean] 
console.log(toString.call(123)); // [object Number] 
console.log(toString.call('123')); // [object String] 
console.log(toString.call({})); // [object Object] 
console.log(toString.call([])); // [object Array] 
console.log(toString.call(function(){})); // [object Function] 
console.log(toString.call(new Date())); // [object Date] 
//console.log(toString.call(reg)); // [object RegExp] 
//console.log(toString.call(err)); // [object Error] 
//console.log(toString.call(arg)); // [object Arguments]

三、数据检测类型方法:

/** 
* @desc 数据类型检测 
* @param obj 待检测的数据 
* @return {String} 类型字符串
*/
function type(obj) { 
   return typeof obj !== "object" ? typeof obj : Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

四、实现深拷贝:

/**
* deepClone() 深拷贝方法
* obj 需要拷贝的数据
**/
function deepClone(obj={}){

  //1.先判断obj是值类型还是引用类型数据
  if( typeof obj !=='object'|| obj==unll){
    return obj;
  }
  
  //2.再判断obj是数组[]还是对象{}
  let resulet;
  (obj instanceof Array)?resulet =[]:resulet={};
  
  //3.循环
  for(let key in obj){
      //4.保证key不是原始对象的属性
     if(object.hasOwnProperth(key)){
      //递归
     resulet[key]= deepClone(obj[key])
       
     } 
  }
  return resulet;
}