js判断数据类型

116 阅读1分钟

js中有很多时候需要判断类型,

比如是否是数组,是否是object,是否是function,是否是正则,是否是string,是否是number等等...

那么怎么做呢?

我们最常用的是使用typeof

js中几种数据类型(ts暂且不说):

typeof始终返回一个string类型的字符串,并且都是小写的;

1,string

我们判断string类型的时候,可以直接用typeof;

typeof 'aa' === "string";

typeof String(1) === 'string'; // String 将任意值转换为字符串,比 toString 更安全

2,number

typeof 232 === "number"; 

typeof 3.142 === 'number'; 

typeof Math.LN2 === 'number'; 

typeof Infinity === 'number'; 

typeof NaN === 'number';

3,boolean

typeof true === 'boolean'; 

typeof false === 'boolean'; 

typeof Boolean(1) === 'boolean'; // Boolean() 会基于参数是真值还是虚值进行转换 

typeof !!(1) === 'boolean'; // 两次调用 !(逻辑非)运算符相当于 Boolean()

4,function

typeof function() {} === 'function'; 

typeof class C {} === 'function';

typeof Math.sin === 'function';

5,object


//在判断数据类型为复杂数据类型,比如object的时候,一定要先去除null。 

typeof null === "object"; 

if(a !== null){ 

    typeof a; ///之后开始判断 

}

6,如果是new出来的对象,则将返回对象object;如果是new的Function,则还是function;

const func = new Function(); 
typeof func; // "function" 
const num = new Number(100); 
typeof num; // "object" 
const str = new String("String"); 
typeof str; // "object"

通过以上列举,我们知道typeof其实可以判断类型的。除数组之外,那么数组怎么判断呢?因为判断数组用typeof,直接返回object;

上硬菜!

//判断是否是数组
let a = []; 

//方法一 
Array.isArray(a); 

//方法二 
Object.prototype.toString() == "[object, Array]";

以上是参照developer.mozilla.org/zh-CN/docs/…