javascript - javascript中如何测试变量是否是某种类型对象的数组?

标签 javascript arrays object types

我有一个对象。让我们称之为foo。我希望 bar (一个函数或另一个对象,并不重要)获取一个 foo 数组。我还想确保它确实得到了这一点,所以我想测试该类型。

但是,根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeoftypeof 运算符不处理数组。它将它们视为对象。经过一番挖掘后,我发现 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/

相关文章:

Json 多数组的 C# Web API POST 方法

javascript - 我连续推送了2条消息到消息队列,但它们似乎没有被连续调用

javascript - 无法使用 angular.js 将值设置为下拉所选值

javascript - 为什么我的 'position:fixed' 导航栏显示在网页底部而不是移动视口(viewport)底部?

两个不同 vector 中的 C++ 相同对象

c# - 动态与对象类型

php - 如何创建使用对象上下文的运行时函数?

javascript - 计算 Javascript 数组中相同的最近值

java - 将数组中的输入值加 1?结果是 [1,1,1..]

arrays - 无法将 tibble 转换为 R 中的数组?