javascript - 为什么数字不是具有 typeof 和 instanceof 的 Number 实例?

标签 javascript

我需要从数组中获取给定类型的所有元素,如下所示 [{ a: 'a' }, 4,/a-z/, 6, [1, 2, 3], i=>i ],当我提供 Number 类型作为 ofType(type) 的参数时,它返回 [ ] :

Array.prototype.ofType = function (type) {
    let newArr = []; 
    this.forEach(i => i instanceof type ? newArr.push(i) : newArr );
    return newArr
}

在其他情况下,例如[{ a: 'a' }, 4,/a-z/, 6, [1, 2, 3], i=>i].ofType(RegExp)它工作正常。

最佳答案

JavaScript 有数字基元和数字对象。数字基元不是 instanceof任何东西,因为它不是对象,只有对象才是某物的“实例”(“实例”是面向对象编程的术语);所以instanceof对于基元没有用。

那就是typeof typeof 的结果进来了。对于原始数是 "number" .

instanceof需要构造函数作为右侧操作数,您可以拥有 ofType函数分支基于是否获取函数或字符串,使用 instanceof如果它是一个函数并且 typeof如果它是一个字符串。使用您的forEach循环:

Array.prototype.ofType = function (type) {
    let newArr = []; 
    if (typeof type === "string") {
        this.forEach(i => typeof i === type ? newArr.push(i) : newArr );
    } else {
        this.forEach(i => i instanceof type ? newArr.push(i) : newArr );
    }
    return newArr;
};

但我不会使用forEach为此,我会使用 filter :

Array.prototype.ofType = function (type) {
    let newArr;
    if (typeof type === "string") {
        newArr = this.filter(i => typeof i === type);
    } else {
        newArr = this.filter(i => i instanceof type);
    }
    return newArr;
};

此外,我强烈建议不要将可枚举属性添加到 Array.prototype ,它破坏了错误使用 for-in 的代码在数组上循环。使用Object.defineProperty相反:

Object.defineProperty(Array.prototype, "ofType", {
    value(type) {
        let newArr;
        if (typeof type === "string") {
            newArr = this.filter(i => typeof i === type);
        } else {
            newArr = this.filter(i => i instanceof type);
        }
        return newArr;
    },
    writable: true,
    configurable: true,
    enumerable: false // This is the default, so you could leave it off
});

实例:

Object.defineProperty(Array.prototype, "ofType", {
    value(type) {
        let newArr;
        if (typeof type === "string") {
            newArr = this.filter(i => typeof i === type);
        } else {
            newArr = this.filter(i => i instanceof type);
        }
        return newArr;
    },
    writable: true,
    configurable: true,
    enumerable: false // This is the default, so you could leave it off
});

console.log([1, "2", 3, "4"].ofType("number"));

console.log([new Date, "2", new Date, "4"].ofType(Date));

关于javascript - 为什么数字不是具有 typeof 和 instanceof 的 Number 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61055309/

相关文章:

javascript - 将调试路径复制到对象数据 Visual Studio 代码 javascript

javascript - 根据溢出隐藏和显示一些div

javascript - 解析包含日期的 JSON 字符串时出现问题

javascript - 什么允许 id 属性的字符,以便 jQuery 选择器不会抛出异常?

JavaScript 回调函数

用于增强参数化构建的 Javascript

javascript - 然后jquery多个deferreds

javascript - 如何从c#中的javascript对象获取值

javascript - 简单的ajax发布未捕获的ReferenceError

javascript - 在气泡图上强制模拟文本不起作用