I have a variable a
that can be either an object or an array of objects. I have an array array
.
I want to append a
to array
, so I thought of using either Array.prototype.push.call
or Array.prototype.push.apply
with a ternary operator as follows:
var a = "hello"; // or var a = ["hello", "world"];
var array = [];
var append = ($.isArray(a)) ? Array.prototype.push.apply : Array.prototype.push.call;
append(array, a); // Uncaught TypeError: undefined is not a function
($
being jQuery)
I'm new to JavaScript and I guess there is a good reason why this doesn't work but I couldn't find it. Can't apply
or call
be assigned to a variable? (They are not real functions?) Or is something missing on the call to append()
?
Note: I know I could do this with if/else
but I'd rather like to understand why I can't assign these methods to a variable and call it.
Minor additional question: I want to do this because I get a
from a JSON API and if I understand correctly, JSON can't contain arrays of one single object. Although I feel that what I'm trying to do must be very common, I also couldn't find how other developers deal with this. Is there a better way than testing whether a
is an array or not and use apply()
or not accordingly?