1

I want to create array, copy of an existing array, but not an instance of it. How i can do this in one line?

array1 = new Array('orange', 'red', 'blue', 'green');
array2 = new Array.apply(this, array1);

// Uncaught TypeError: function apply() is not a constructor 
S.B.
  • 2,920
  • 1
  • 17
  • 25
Artiom
  • 153
  • 1
  • 6

5 Answers5

3

Array.prototype.slice is the method you're looking for. You may also want to use a literal when defining your Array.

var array1, array2;

array1 = ['orange', 'red', 'blue', 'green'];
array2 = array1.slice();

Now have

array1.join() === array2.join(); // true
array1 === array2; // false
Paul S.
  • 64,864
  • 9
  • 122
  • 138
2

Omit the new to make apply work (otherwise it would be interpreted as new (Array.apply)(…)). Since the Array constructor doesn't require a new and can be called as a function as well, it would be as simple as:

array1 = new Array('orange', 'red', 'blue', 'green');
array2 = Array.apply(this, array1);

Related question: Use of .apply() with 'new' operator. Is this possible?

However, you shouldn't need to use the Array constructor at all, especially because it doesn't work well with single-numeric-element arrays. Better:

var array1 = ['orange', 'red', 'blue', 'green'];
var array2 = array1.slice();
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1
array2 = array1.slice(0);

Returns a new array containing all items from the source array starting from the index given in the argument, which in this case is zero so the whole array.

Note that if any of your array items are themselves objects (eg. multi-dimensional arrays) then the new array will still point to the same instance of those arrays:

array1 = [1,[2,3]];
array2 = array1.slice(0);
array2[0] = 4;
array2[1][0] = 5;

// array1 is now [1,[5,3]]!
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

According to this article, you only need to do an array slice.

var array2 = array1.slice(0);

That article also covers deep cloning.

0

Use array.slice

var copy = original.slice(0);

More on array.slice

James Lim
  • 12,915
  • 4
  • 40
  • 65