1. ## Copy array?

I have a multi-dimension array that I want to copy.

Doing new = old creates a reference, and new = old.slice() only creates a one-level deep copy.

How can I copy my ENTIRE array?

2. Code:
```Array.prototype.copy=function(){
var A=[];
var L=this.length;
for(var i=0;i<L;i++){
A.push(this[i]);
}
return A;
}```
Eg:

Code:
```var A=[1,2,3,[4,5,6]];
var B=A.copy();
1
2
3
4, 5, 6
*/```

3. There is really no need to extend the Array object to copy an array. Do this instead
Code:
```var oldArray= [1,2,3,[4,5,6]];
var newArray = oldArray.slice();

// Add element to newArray, oldArray should not get this value
newArray.push(7);

// Check that the above statement is true

4. mrhoo's approach is correct but he forgot the recursion:

Code:
```Array.prototype.copy = function() {
var a = [];
for(var i = 0; i < this.length; i++)
a.push(this[i].copy ?
this[i].copy() : this[i]);
return a;
}```
Test

Code:
```a = [1, [21, 22], 3];
b = a.copy()
b[0] = "foo"
b[1][0] = "bar"

5. Right you are, stereo-
but to be complete, we ought to include arrays that have
objects for members:

Code:
```Array.prototype.copy=function(){
var A=[], wot;
var L=this.length;
for(var i=0;i<L;i++){
var tem=this[i];
wot=tem.constructor;
if(wot){
if(wot==Array || wot==Object){
A.push(new wot)
for(var p in tem){
A[i][p]=(tem[p].copy? tem[p].copy():tem[p]);
}
continue;
}
}
A.push(tem);
}
return A;
}```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•