yossi
yossi

Reputation: 3164

jQuery $.extend - to extend an Array

Using the $.extend is working, but it returns an Object and not a native Array, so the push() won't work.
How can I extend an array, using the jQuery.extend?

var x =[1,2];
var y = $.extend({},x);
y.push(3) // fail


edit: The array WILL contain objects, so - the slice() won't do the trick

Upvotes: 1

Views: 4274

Answers (2)

Teddy
Teddy

Reputation: 4233

You have to give the input object as an array.

jQuery.extend(['c'], ['a','b']) 

Above works as expected. Index 0 is overridden as 'a'. And index 1 is assigned 'b'. And the result is an instanceof Array.

Although, many inbuilt methods are getting added as properties on the resultant array, which might get in the way sometimes.

enter image description here

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115232

No need of jQuery at all use Array#concat method.

var x =[1,2];
var y = x.concat([3,4]);
y.push(3) 

Upvotes: 3

Related Questions