1. 程式人生 > 實用技巧 >56、js中檢測資料型別的幾種方式

56、js中檢測資料型別的幾種方式

js中檢測資料型別的幾種方式

1、typeof 一元運算子,用來檢測資料型別。只可以檢測number,string,boolean,object,function,undefined。 對於基本資料型別是沒有問題的,但是遇到引用資料型別是不起作用的(無法細分物件)
1 2 3 4 5 6 7 8 9 10 letstr ='{}'; letfn =function(){}; letobj = {}; letary = []; letrg = /\d/; console.log(typeofstr);//string console.log(typeoffn);//function
console.log(typeofobj);//object console.log(typeofary);//object console.log(typeofrg);//object<br><br>

  

2、instanceof(二元運算子,需要兩個運算元) 檢測某個物件是不是另外一個物件的例項 instanceof只能用來判斷物件和函式,不能用來判斷字串和數字
let arr = [1,2,3];
console.log(arr instanceof Array);//true  檢測arr是不是內建類Array的例項

3、Object.prototype.toString.call JavaScript中,通過Object.prototype.toString方法,判斷某個物件值屬於哪種內建型別
let date = new Date;
console.log(Object.prototype.toString.call(date));//[object Date]
let re = '/\d+g/';
console.log(Object.prototype.toString.call(re));//[object String]
let sz = [2,3,4];
console.log(Object.prototype.toString.call(sz));//[object Array]
let hs = function(){};
console.log(Object.prototype.toString.call(hs));//[object Function]