toString 本来是用来做字符串转换的,不过现在流行用来做变量类型的检查了。这里也的一个函数,方便检查变量的类型,可以用来代替 typeof
function getType(o) {
var _t; return ((_t = typeof(o)) == "object" ? o==null && "null" ||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
getType(null); //null
本文介绍了一个JavaScript函数,用于检查变量的类型,包括基本类型如字符串、数字、布尔值,以及复杂类型如数组、对象、函数等。该函数通过typeof操作符结合Object.prototype.toString方法实现了对各种类型的有效区分。
3953

被折叠的 条评论
为什么被折叠?



