1

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
yossi
  • 3,090
  • 7
  • 45
  • 65
  • @PranavCBalan well, that's what i wrote.. and this is my question – yossi Nov 07 '16 at 06:49
  • Possible duplicate of [Is there a method to clone an array in jQuery?](http://stackoverflow.com/questions/3775480/is-there-a-method-to-clone-an-array-in-jquery) – styopdev Nov 07 '16 at 06:49
  • No where it saying that it will return an array... – Pranav C Balan Nov 07 '16 at 06:50
  • jQuery.extend(['c'], ['a','b']) works. 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. – Teddy Oct 24 '18 at 12:42

2 Answers2

3

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

var x =[1,2];
var y = x.concat([3,4]);
y.push(3) 
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • shame on me. you are correct. thanks. (too much of that JQ) – yossi Nov 07 '16 at 06:55
  • 1
    @yossi : glad to help you..... if you want to push the value array into an existing array then.... `[].push.apply(x, [1,2,3])` this will push the array values to `x` – Pranav C Balan Nov 07 '16 at 06:57
0

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

Teddy
  • 4,009
  • 2
  • 33
  • 55