js中检测数据类型的四种方法

typeof

先看一下用法:

console.log(typeof "");
console.log(typeof 1);
console.log(typeof true);
console.log(typeof null);
console.log(typeof undefined);
console.log(typeof []);
console.log(typeof function(){});
console.log(typeof {});

输出结果如下:

string
number
boolean
object
undefined
object
function
object

小结
typeof可以用于检测基本类型,但碰到引用类型均返回为object。

instanceof

看一下用法:

console.log("1" instanceof String);
console.log(1 instanceof Number);
console.log(true instanceof Boolean);
console.log([] instanceof Array);
console.log(function(){} instanceof Function);
console.log({} instanceof Object);

输出结果如下:

false
false
false
true
true
true

小结
不难看出,instanceof可以用于引用类型的检测,但对于基本类型是不生效的,另外,不能用于检测null和undefined。

constructor

先看一下用法:

console.log(("1").constructor === String);
console.log((1).constructor === Number);
console.log((true).constructor === Boolean);
console.log(([]).constructor === Array);
console.log((function() {}).constructor === Function);
console.log(({}).constructor === Object);

输出结果:

true
true
true
true
true
true

撇去null和undefined,似乎说constructor能用于检测js的基本类型和引用类型。但当涉及到原型和继承的时候,便出现了问题,如下:

function fun() {};

fun.prototype = new Array();

let f = new fun();

console.log(f.constructor===fun);
console.log(f.constructor===Array);

在这里,我们先是定义了一个函数fun,并将该函数的原型指向了数组,同时,声明了一个f为fun的类型,然后利用constructor进行检测时,结果如下:

false
true

小结
撇去null和undefined,constructor能用于检测js的基本类型和引用类型,但当对象的原型更改之后,constructor便失效了。

Object.prototype.toString.call()

用法:

var test = Object.prototype.toString;

console.log(test.call("str"));
console.log(test.call(1));
console.log(test.call(true));
console.log(test.call(null));
console.log(test.call(undefined));
console.log(test.call([]));
console.log(test.call(function() {}));
console.log(test.call({}));

结果:

[object String]
[object Number]
[object Boolean]
[object Null]
[object Undefined]
[object Array]
[object Function]
[object Object]

这样一看,似乎能满足js的所有数据类型,那我们看下继承之后是否能检测出来

function fun() {};

fun.prototype = new Array();

let f = new fun();

console.log(Object.prototype.toString.call(fun))
console.log(Object.prototype.toString.call(f))

结果:

[object Function]
[object Object]

小结
可以看出,Object.prototype.toString.call()可用于检测js所有的数据类型。

转载自: https://segmentfault.com/a/1190000019259209

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值