我有一个对象。让我们称之为foo
。我希望 bar
(一个函数或另一个对象,并不重要)获取一个 foo
数组。我还想确保它确实得到了这一点,所以我想测试该类型。
但是,根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof ,typeof
运算符不处理数组。它将它们视为对象。经过一番挖掘后,我发现 How to check if an object is an array? ,说使用 Array.isArray 来测试它是否是一个数组,但是除了循环所有内容之外,有没有办法测试给定的变量是否是一个数组 foo
?
或者我是否记得正确 new Foo()===new Foo()
从来都不是真的?如果是这样,这是否意味着无法测试我想要的东西?
最佳答案
but other than looping over everything, is there a way to test whether or not the given variable is an array of foo?
不,但是这样的循环非常简单,只需检查每个
项目是否通过instanceof
检查:
function Foo() {}
function bar(arr) {
if (!arr.every(item => item instanceof Foo)) {
console.log('Bad arguments');
return;
}
console.log('OK');
}
const f = new Foo();
bar([f]);
bar([1]);
关于javascript - javascript中如何测试变量是否是某种类型对象的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60186481/