我想制作一个多维数组的克隆,以便我可以使用克隆数组进行arround而不会影响主数组.
Array.prototype.clone = function () {
var newArray = new Array(this.length);
for(var i=0; i < this.length; i++ ){
newArray[i] = this[i];
}
return newArray;
};
Run Code Online (Sandbox Code Playgroud)
但问题是,因为它使用数组原型,所以它将克隆我的所有数组.所以任何机构都可以告诉我这样做的最佳方法是什么.
meo*_*ouw 10
vsync是正确的,我的第一个答案没有处理var a = [[1,2],[3,4]];
所以这里是一个改进的版本
var a = [[1,2],[3,4]];
Array.prototype.clone = function() {
var arr = this.slice(0);
for( var i = 0; i < this.length; i++ ) {
if( this[i].clone ) {
//recursion
arr[i] = this[i].clone();
}
}
return arr;
}
var b = a.clone()
console.log(a);
console.log(b);
b[1][0] = 'a';
console.log(a);
console.log(b);
//[[1, 2], [3, 4]]
//[[1, 2], [3, 4]]
//[[1, 2], [3, 4]]
//[[1, 2], ["a", 4]]
Run Code Online (Sandbox Code Playgroud)
你需要使用递归
var a = [1,2,[3,4,[5,6]]];
Array.prototype.clone = function() {
var arr = [];
for( var i = 0; i < this.length; i++ ) {
// if( this[i].constructor == this.constructor ) {
if( this[i].clone ) {
//recursion
arr[i] = this[i].clone();
break;
}
arr[i] = this[i];
}
return arr;
}
var b = a.clone()
console.log(a);
console.log(b);
b[2][0] = 'a';
console.log(a);
console.log(b);
/*
[1, 2, [3, 4, [5, 6]]]
[1, 2, [3, 4, [5, 6]]]
[1, 2, [3, 4, [5, 6]]]
[1, 2, ["a", 4, [5, 6]]]
*/
Run Code Online (Sandbox Code Playgroud)
原始数组中的任何其他对象都将通过引用复制