typeof
不能很好地工作,例如,typeof null
在 object
上返回。除了这种改进的内置或定制替代品之外,还有更好的替代品吗?
最佳答案
参见 Fixing the JavaScript typeof Operator .
简而言之,你可以使用这个函数:
var toType = function (obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
toType(null); // -> "null"
toType({}); // -> "object"
toType([]); // -> "array"
toType("asdf"); // -> "string"
toType(/asdf/); // -> "regexp"
// etc.
您应该查看该文章以详细了解它为何如此工作以及您可以从中得到什么。它总是返回一个字符串,就像 typeof
一样。
关于javascript - typeof 函数修复/替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11108877/