javascript判断参数类型

type 2; //输出:"number"
var a = function(){};typeof a;或typeof (function(){}); //输出:"function"
typeof '22'; //输出:"string"
typeof undefined;或var a;typeof a; //输出:"undefined"
var a = true;typeof a; //输出:"boolean"
var a = null;typeof a; //输出:"object"
var a = [1,2];typeof a; //输出:"object"
var a = {"b":2};typeof a; //输出:"object"
...; //包括其他javascript原生类对象(Object、Function、Array、String、Boolean、Number、Date、RegExp、Error、EvalError、RangeError、ReferenceError、SyntaxError、TypeError、URIError等等,很有很多其他对象,如HTML标签原始对象等等)输出值都为"object"

这里面包含了js里面的五种数据类型(number、string、boolean、undefined、object)和函数类型(function),那怎么去区分对象,数组和null这几种类型呢?接下来我们介绍使用Object.prototype.toString.call()这个更强大的"原生原型扩展函数"。

Object.prototype.toString.call(2); //输出:"[object Number]"
Object.prototype.toString.call(undefined);或var a;Object.prototype.toString.call(a); //输出:"[object Undefined]"
var a = function(){};Object.prototype.toString.call(a);或Object.prototype.toString.call((function(){})); //输出:"[object Function]"
Object.prototype.toString.call("22"); //输出:"[object String]"
var a = true;Object.prototype.toString.call(a); //输出:"[object Boolean]"
var a = null;Object.prototype.toString.call(a); //输出:"[object Null]"
var a = [1,2];Object.prototype.toString.call(a); //输出:"[object Array]"
var a = {"b":2};Object.prototype.toString.call(a); //输出:"[object Object]"
//以下为原生对象输出
var a = new Object();Object.prototype.toString.call(a); //输出:"[object Object]"
var a = new Function();Object.prototype.toString.call(a); //输出:"[object Function]"
var a = new Array();Object.prototype.toString.call(a); //输出:"[object Array]"
var a = new String();Object.prototype.toString.call(a); //输出:"[object String]"
var a = new Boolean();Object.prototype.toString.call(a); //输出:"[object Boolean]"
var a = new Number();Object.prototype.toString.call(a); //输出:"[object Number]"
var a = new Date();Object.prototype.toString.call(a); //输出:"[object Date]"
var a = new RegExp();Object.prototype.toString.call(a); //输出:"[object RegExp]"
var a = new Error();Object.prototype.toString.call(a); //输出:"[object Error]",类型Error、EvalError、RangeError、ReferenceError、SyntaxError、TypeError、URIError等等输出值相同
...; //还有很多其他对象,如HTML标签原始对象等等

由上可知,可通过这些方式通过写工具方法的方式判断参数类型。

猜你喜欢

转载自blog.csdn.net/A123638/article/details/82589541