I have an object that has several members, each an array. I have another object that includes this object. In the constructor for the outer object, I’d like to say that if the user passes in an object, I use that as the value for the inner object. If they pass in an array, I create a new object, using the passed-in array for one of the values and generating the other values by some rules for defaults.
That is:
class Outer {
constructor(inner) {
if (inner is an object) { // this is the statement I don't know how to write
this.inner=inner
}
else {
this.inner={"value1":inner}
this.inner.value2=... blah blah blah
}
}
In my first draft I said, if (typeof inner == "object"). That didn’t work because for arrays it returns true. I guess an array is a special case of an object.
So I tried to do it the other way and say inner instanceof Array. That didn’t work because for objects it returned undefined.
So … is there some way that I can test if a value is an object versus an array?
If it’s relevant, in the new Outer I want to pass the value in as a literal, i.e. I might say new Outer([1,2,3]) or new Outer({"value1":[1,2,3],"value2":[2,3,4]).
And yes, I know I can solve the problem by just always passing in an object, and that’s what I’m going to do for at least the short term. I was thinking that the New Outer was cleaner if I could say new Outer([1,2,3]) rather than new Outer({"value1":[1,2,3]}). But it’s not that big a deal. But I’d like to know how to do this for future reference, at least.
2
Answers
Here is what you need to do.
Arrays are a special type of object only in JavaScript. So, when we use the typeof operator it gives object.
But the Array class has some methods like isArray(), Which can be used to identify if something is an Array.
So, this function returns a boolean.
I hope it helps. Cheers 🤜🏻🤛🏻
You could check the prototype:
Or use
Array.isArray()
: