Mark Gardner
Mark Gardner

Reputation: 472

How to test if a variable is an array of a certain type of objects in javascript?

I have an object. Let us call it foo. I want bar (a function, or another object, doesn't really matter) to take an array of foo. I also want to make sure that it is indeed getting that, so I want to test the type.

However, according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof , the typeof operator doesn't do arrays. It treats them as objects. After some digging around, I found How to check if an object is an array? , saying to use Array.isArray to test whether or not it is an array, but other than looping over everything, is there a way to test whether or not the given variable is an array of foo?

Or do I remember correctly that new Foo()===new Foo() is never true? If so, does this meant that it is impossible to test what I want?

Upvotes: 0

Views: 45

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

but other than looping over everything, is there a way to test whether or not the given variable is an array of foo?

No, but such looping is quite easy, just check if every item passes an instanceof check:

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]);

Upvotes: 1

Related Questions