0

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?

Mark Gardner
  • 442
  • 1
  • 6
  • 18

1 Answers1

1

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]);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320