JavaScript中检测数据类型的四种方式;

1、typeof:不能检测Object下面的细分,比如Array/等

2、instanceof:在原型链的继承;

 

f不是一个数组;但是由于继承了Array这个类,所以f instanceof Array也是true了,不精确;

function Fn(){

}
Fn.prototype=new Array;
var f=new Fn();
console.log(f instanceof Fn);//true
console.log(f instanceof Object);//true
console.log(f instanceof Array);//true

3、constructor;

4、调用Object基类上的tostring来检测我们的数据类型;这个方法不是将他转化为字符串的,而是返回当前实例所属的类“[Object 类]”

例如:”[object String]”、”[object Number]”、”[object Array]”…..

    console.log(Object.prototype.toString.call("朱安邦"));
console.log(Object.prototype.toString.apply(123));
// 简写成:
console.log([].toString.call(123))
console.log(tools.isTypeOf(123));
var ary = [];
console.log(tools.isType(ary, "String"));
function isType( value,type) {
type = type|| "Object";
var reg = new RegExp("\\[object " + type + "\\]", "i");
return reg.test([].toString.call(value));
}
var a=1111
,
b="11111",
c=false,
d=[1,2,3,4,5],
e={},
f=/^ | $/i;
console.log(isType(a,"Number"
));
console.log(isType(b,"String"
));
console.log(isType(c,"Boolean"
));
console.log(isType(d,"Array"
));
console.log(isType(e,"Object"
));
console.log(isType(f,"RegExp"
));

·

····