任何编写 JS 的开发人员迟早都会遇到这种令人恼火的行为:
typeof []; // 'object'
虽然有一些解决方法,例如 instanceof
和访问变量的 .constructor
属性,但我想到的是:
Array.prototype.TYPE = 'Array';
String.prototype.TYPE = 'String';
Boolean.prototype.TYPE = 'Boolean';
Object.prototype.TYPE = 'Object';
RegExp.prototype.TYPE = 'RegExp';
Number.prototype.TYPE = 'Number';
// and therefore:
[1,2,'bar', {baz: 'foo'}].TYPE === 'Array'; // true
"But life itself, my wife, and all the world / Are not with me esteemed above thy life".TYPE // 'String'
(42).TYPE === 'Number'; // true
// and so on
我知道修改原生原型(prototype)通常是不受欢迎的,也就是说,这个“模式”还有其他问题吗?
更新:
一些评论提供了替代解决方案,例如使用 Object.prototype.toString
等。这些当然都是有其用例的有效方法。但是,我最感兴趣的是是否在某些情况下向 native 构造函数原型(prototype)添加属性实际上会导致问题:)
更新:
更安全的方法?
Array.prototype.getType = function() {return 'Array'};
String.prototype.getType = function() {return 'String'};
Boolean.prototype.getType = function() {return 'Boolean'};
Object.prototype.getType = function() {return 'Object'};
RegExp.prototype.getType = function() {return 'RegExp'};
Number.prototype.getType = function() {return 'Number'};
最佳答案
道格拉斯·克罗克福德 recommends writing your own typeOf
function正是出于这个原因:
... The new
typeOf
global function is intended to replace the defectivetypeof
operator. It produces the same result as typeof, except that it returns'null'
fornull
and'array'
for arrays.
他是这样实现的:
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (typeof value.length === 'number' &&
!(value.propertyIsEnumerable('length')) &&
typeof value.splice === 'function') {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
typeOf({}) //=> "object"
typeOf([]) //=> "array"
关于javascript - 这是确定 JavaScript 变量类型的有效方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24088842/