您的位置:首页 > Web前端 > JavaScript

js中数据类型检测

2017-11-13 13:17 176 查看

我们熟知的类型检测方式有三种:

1.typeof:

用于检测基本数据类型string number
布尔 undefined (不能用来检验复杂数据类型和null);

能检测:

1.undefined

console.log(typeof undefined);//undefined

2.boolean

console.log(typeof true);//boolean

3.string

console.log(typeof '9');//string

4.number

console.log(typeof 5);//number

5.function

console.log(typeof function(){});//function

不能检测

1.null

console.log(typeof null);//object

2.object

console.log(typeof {});//object

3.Array

console.log(typeof []);//object

2.instanceof

instanceof 用于判断一个变量是否某个对象的实例

其中在判断function,array的时候会出错。

 var a=new Array();console.log(a instanceof Object)

true

 var a=function(){};console.log(a instanceof Object)

True

这并不是我们希望看到的,故我们使用Object.prototype.toString.call(数据名)来解决。

3.Object.prototype.toString.call(数据名);

var a = new Object();

Object.prototype.toString.call(a);//[Object Object];

var a = new Array();

Object.prototype.toString.call(a);//[Object Array];

var a = function(){};

Object.prototype.toString.call(a);//[Object Function];

故我们可以通过原型的toString方法结合call来判断复杂数据类型。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: