JS 数据类型判断的几个函数
1、typeof
var a = 10;
var b = "string";
var c = true;
var d = new Array();
var e = {a:0,b:0};
var f = function(){};
var g = /^[a-zA-Z]$/;
var h = new Date();
var i = new Error();
var j = undefined;
var k = null;
console.log(
typeof a,
typeof b,
typeof c,
typeof d,
typeof e,
typeof f,
typeof g,
typeof h,
typeof i,
typeof j,
typeof k
);
// 输出结果:
number string boolean object object function object object object undefined object
可使用 typeof 精确判断 “<span style="color: #800000;">number</span> <span style="color: #0000ff;">string </span> <span style="color: #ff00ff;">boolean</span> <span style="color: #993300;">function</span> <span style="color: #008000;">undefined ” </span>类型
2、instanceof
console.log(
a instanceof Number,
b instanceof String,
c instanceof Boolean,
d instanceof Array,
e instanceof Object,
f instanceof Function,
g instanceof RegExp,
h instanceof Date,
i instanceof Error,
j instanceof Object,
k instanceof Object
);
// 输出结果:
false false false true true true true true true false false
a、b、c 需使用 new Number(10) 的形式才为 true, j、k 的类型无法判断
3、constructor
console.log(
a.constructor === Number,
b.constructor === String,
c.constructor === Boolean,
d.constructor === Array,
e.constructor === Object,
f.constructor === Function,
g.constructor === RegExp,
h.constructor === Date,
i.constructor === Error,
);
// 输出结果:
true true true true true true true true true
除了 j 和 k,其他类型的变量均能使用 constructor 判断
4、Object.prototype.toString.call
console.log(
Object.prototype.toString.call(a),
Object.prototype.toString.call(b),
Object.prototype.toString.call(c),
Object.prototype.toString.call(d),
Object.prototype.toString.call(e),
Object.prototype.toString.call(f),
Object.prototype.toString.call(g),
Object.prototype.toString.call(h),
Object.prototype.toString.call(i),
Object.prototype.toString.call(j),
Object.prototype.toString.call(k)
);
// 输出结果:(为字符串)
[object Number] [object String] [object Boolean]
[object Array] [object Object] [object Function]
[object RegExp] [object Date] [object Error]
[object Undefined] [object Null]
可以使用 Object.prototype.toString.call(a) === "object Number" 来判断
5、$.type
console.log(
$.type(a),
$.type(b),
$.type(c),
$.type(d),
$.type(e),
$.type(f),
$.type(g),
$.type(h),
$.type(i),
$.type(j),
$.type(k)
);
// 输出结果:
number string boolean array object function regexp date error undefined null
但是需要导入 jquery 插件,准确度还是很高的
以下为几个函数对照表,仅为参考