日期:2014-05-16  浏览次数:20328 次

javascript如何检查变量类型

toString 本来是用来做字符串转换的,不过现在流行用来做变量类型的检查了。网页 教学网这里也写了一个函数,方便检查变量的类型,可以用来代替 typeof

function getType(o) {
  var _t; return ((_t = typeof(o)) == "object" ? Object.prototype.toString.call(o).slice(8,-1):_t).toLowerCase();
}
?

执行结果:

getType("abc" ); //string
getType(true ); //boolean
getType(123); //number
getType([]); //array
getType({}); //object
getType(function (){}); //function
getType(new Date ); //date
getType(new RegExp ); //regexp
getType(Math ); //math

?

[转自 :http://www.jzxue.com/wangzhankaifa/javascript-ajax/201103/29-6932.html ]