1. 程式人生 > >JS區分數據類型

JS區分數據類型

prototype height cal ber type typeof ret efi num

JS中的typeof方法可以查看數據的類型,如下:

1 console.log(typeof 2); // number
2 console.log(typeof "2"); // string
3 console.log(typeof true); // boolean
4 console.log(typeof [2]); // object
5 console.log(typeof {name:2});// object
6 console.log(typeof function(){return 2});// function
7 console.log(typeof new Date());// object
8 console.log(typeof null); // object 9 console.log(typeof undefined);// undefined

但typeof只能區分數字、字符串、布爾值、方法及undefined,其他的對象、數組、日期、null等均為object,還是沒能區分開,

我們可以利用Object.prototype.toString.call實現。

 1 var getType = Object.prototype.toString;
 2 var res = getType.call(2);
 3 res = getType.call("2");
 4 res = getType.call(true
); 5 res = getType.call([2]); 6 res = getType.call({name:2}); 7 res = getType.call(function(){}); 8 res = getType.call(new Date()); 9 res = getType.call(null); 10 res = getType.call(undefined);

輸出結果依次為:

1 [object Number]
2 [object String]
3 [object Boolean]
4 [object Array]
5 [object Object]
6 [object Function] 7 [object Date] 8 [object Null] 9 [object Undefined]

這樣就能具體區分JS中的數據類型了。

原理請參考這裏。

JS區分數據類型