javascript - 这是确定 JavaScript 变量类型的有效方法吗?

标签 javascript variables types

任何编写 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 defective typeof operator. It produces the same result as typeof, except that it returns 'null' for null 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/

相关文章:

javascript - 如何在后台运行服务器上的 Typescript 文件?

javascript - 显示来自 jSON 对象的值

variables - Fortran 模块和全局变量

相同类型的Powershell参数集

javascript - 是否需要初始化在 Javascript 中作为 "class"构造函数参数传递的变量?

javascript - 使用正则表达式对 URL 进行 Trix 验证

javascript - 键入时如何在双括号之间替换字符串?

php - 更新已设置的 php 变量

php - 在 mysql 查询的 WHERE 子句中使用 php 变量

python - Union 赋值中的不兼容类型