JS 准确判断变量类型

2019-11-28  本文已影响0人  wcmoon

JS 提供了typeof 方法,但是该方法对 array 和 null 等类型并没有区别。不过我们可以用内部[[class]]来做区分。具体看以下代码:

let arr = [1, 2,3];
let num = 1;
let str = '1';
let bool = true;
let und = undefined;
let nul = null;
let func = function () {

};
let date = new Date();
let reg =  new RegExp();

let data = [arr, num, str, bool, und, nul, func, date, reg];
console.log('-----typeof-----');
data.forEach((item) => {
    console.log(typeof item);
});
console.log('------class-----');
data.forEach((item) => {
    console.log(Object.prototype.toString.call(item));
});

输出如下

-----typeof-----
object
number
string
boolean
undefined
object
function
object
object
------class-----
[object Array]
[object Number]
[object String]
[object Boolean]
[object Undefined]
[object Null]
[object Function]
[object Date]
[object RegExp]

上一篇下一篇

猜你喜欢

热点阅读