js判断数据类型

发布时间:2020-06-20 09:28:02 作者:梦想代码
来源:网络 阅读:1092

一、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"

推荐阅读:
  1. JS如何判断数据类型
  2. JS精确判断数据类型代码实例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js 数据类型 数据类

上一篇:Glide 缓存流程

下一篇:Ubuntu16.04 vsftp不能用root用户登录解决办法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》