js判断数据类型

1、typeof 直接返回数据类型字段,可是没法判断数组、null、对象数组

typeof 1
"number"app

typeof NaN
"number"ide

typeof "1"
"string"函数

typeof true
"boolean"ui

typeof undefined
"undefined"this

typeof null
"object"prototype

typeof []
"object"regexp

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

2、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

3、使用 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"

相关文章
相关标签/搜索