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?

Aurélien
  • 1,742
  • 1
  • 19
  • 30

2 Answers2

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

Kirill Slatin
  • 6,085
  • 3
  • 18
  • 38
1

You don't need any if, just use concat

var array = [];
var a = "hello"; // or var a = ["hello", "world"]
array = array.concat(a);
taxicala
  • 21,408
  • 7
  • 37
  • 66