如何准確判斷變量的數據類型


在解決上面的問題之前,我們要了解下基本的知識

JS的數據類型有五種基本類型,undefined,null,boolean,number,string。

還有一種復雜的數據類型,object

從儲存方式看,又分為值類型,引用類型,object便是引用類型。

typeof

該操作符只能判斷值類型的數據類型,引用類型無法具體細分

console.log(typeof '123'); // string
console.log(typeof 123); // number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof [1,2]); // object
console.log(typeof {a:1});// object
console.log(typeof /[a]/);// object
console.log(typeof function(){}) // function

上面代碼中,null,數組,對象,正則表達式都是輸出object,但是函數typeof分辨出來了,但並不是函數屬於值類型,函數依然是對象,只是函數的地位很高,所以最開始這門語言在設計時便讓typeof可以分辨出函數。

那么問題來了,如何細分object的數據類型呢

function judgeType(item){
  let type = typeof item;

  //判斷元素是否為數組
  if(type === 'object'){

  	if(Array.isArray(item)){
  		type = 'array';
  	}else if(item == undefined){
  		type = 'null';
  	}else{
  		const temp = item.toString();

	    if(temp[0] === '/'){
	      type = 'regexp';
	    }
  	}
    
  }

  return type;
}

上面的代碼應該不難看懂,就不具體說明了,測試下該函數的准確性

function judgeType(item){
  let type = typeof item;

  //判斷元素是否為數組
  if(type === 'object'){

  	if(Array.isArray(item)){
  		type = 'array';
  	}else if(item == undefined){
  		type = 'null';
  	}else{
  		const temp = item.toString();

	    if(temp[0] === '/'){
	      type = 'regexp';
	    }
  	}
    
  }

  return type;
}

console.log(judgeType('123'));
console.log(judgeType(123) );
console.log(judgeType(true) );
console.log(judgeType(undefined) )
console.log(judgeType(null) ) // null
console.log(judgeType([1,2]) ); // array
console.log(judgeType({a:1}) ); // object
console.log(judgeType(/[a]/) ); // regexp
console.log(judgeType(function(){}) ) 

當然上面的函數並不能判斷Set,Map等對象,輸出的依然是object。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM