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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! What does this setTimeout thing do? I'm not sure I understand the second half of your code.
It was a way of throwing an error in one part of the code while also allowing the other part to work normally. I'll change it to a console.log

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.