js判断数据类型-成都快上网建站

js判断数据类型

一、typeof 直接返回数据类型字段,但是无法判断数组、null、对象

成都创新互联"三网合一"的企业建站思路。企业可建设拥有电脑版、微信版、手机版的企业网站。实现跨屏营销,产品发布一步更新,电脑网络+移动网络一网打尽,满足企业的营销需求!成都创新互联具备承接各种类型的做网站、成都网站建设项目的能力。经过十载的努力的开拓,为不同行业的企事业单位提供了优质的服务,并获得了客户的一致好评。

typeof 1
"number"

typeof NaN
"number"

typeof "1"
"string"

typeof true
"boolean"

typeof undefined
"undefined"

typeof null
"object"

typeof []
"object"

typeof {}
"object"
其中 null, [], {}都返回 "object"

二、instanceof 判断某个实例是不是属于原型

// 构造函数
function Fruit(name, color) {
this.name = name;
this.color = color;
}
var apple = new Fruit("apple", "red");

// (apple != null)
apple instanceof Object // true
apple instanceof Array // false

三、使用 Object.prototype.toString.call()判断

call()方法可以改变this的指向,那么把Object.prototype.toString()方法指向不同的数据类型上面,返回不同的结果

function _typeof(obj){
var s = Object.prototype.toString.call(obj);
return s.match(/[object (.*?)]/)[1].toLowerCase();
};

_typeof([12,3,343]);
"array"

_typeof({name: 'zxc', age: 18});
"object"

_typeof(1);
"number"

_typeof("1");
"string"

_typeof(null);
"null"

_typeof(undefined);
"undefined"

_typeof(NaN);
"number"

_typeof(Date);
"function"

_typeof(new Date());
"date"

_typeof(new RegExp());
"regexp"


标题名称:js判断数据类型
地址分享:http://kswjz.com/article/geiedp.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流