我需要从数组中获取给定类型的所有元素,如下所示 [{ 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/