0

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?

1
  • array = array.concat(a); And it would be easier if a is always an array. Commented Jul 28, 2015 at 21:33

2 Answers 2

2

This happens because call and apply are instance methods. They are critical to the context object this.

Eventually you should execute append.call(Array.prototype.push, array, a) because call or apply need function push to be passed as this

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

Comments

1

You don't need any if, just use concat

var array = [];
var a = "hello"; // or var a = ["hello", "world"]
array = array.concat(a);

1 Comment

True, but this doesn't really answer the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.