1

我有一个函数,它接收 2 个参数:一个变量和一个数据类型的字符串表示(“字符串”、“对象”等):

function typeChecker(variable, dataType) {
    // checks type, returns true or false
}

我想将第二个参数转换为构造函数,这样这个表达式就不会抛出错误:

variable instanceof 'Date'

问题:是否可以转换以下任何一种:

'String'
'Date'
'Object'

对这些:

String
Date
Object
4

2 回答 2

3

这些构造函数都恰好是全局对象的成员(window在浏览器中或global在 Node.js 中),因此您可以执行以下操作之一

variable instanceof window['Date']
variable instanceof global['Date']

如果您的构造函数不作为全局对象的成员存在,您可以检查值的原型链中的任何原型是否与匹配所需字符串constructor的a 相关联:name

function checkIfValueIsOfTypeName(value, typeName) {
    while(value = Object.getPrototypeOf(value)) {
        if(value.constructor && value.constructor.name === typeName) {
            return true;
        }
    }
    return false;
}

这或多或少instanceOf是内部操作的方式,除了instanceOf直接与constructor右侧的值进行比较,而不是将其名称与字符串进行比较,这是您想要做的。

于 2018-08-16T18:34:31.183 回答
0

您可以使用 typeof

console.log(typeof 10);
// output: "number"

console.log(typeof 'name');
// output: "string"

console.log(typeof false);
// output: "boolean"
于 2018-08-16T18:39:38.973 回答