2013-07-19 90 views
1

所以目前我在這裏有一個數組,我想對最後一項進行一些修改並將其推回去。在這裏,我有這樣的代碼:(例如簡化)多維數組參考問題

var array = [ 
       [ [0,1,2], [3,4,5] ] 
      ]; 

//other stuff... 

var add = array[0].slice(); //to clone the array (but not working as expected) 
add[0][0] = 10; 
array.push(add); 

console.log(array); 

而這裏的結果

enter image description here

正如你所看到的,在第一和第二項有它的第一項改爲10。我怎麼解決這個問題?我已經克隆了這個數組。

+0

什麼是切片應該做無參數 – aaronman

+0

@aaronman - 這是用於克隆陣列一招。 –

+0

是的,你知道問題是內部的對象不是新對象的引用 – aaronman

回答

5

Array.prototype.slice()做淺拷貝,所以不會複製嵌套數組。您應該使用深度克隆方法,如this

+1

Ur的回答是好的,但如果你談到slice創建的數組是新的,但是原始的內部對象數組不被複制,但引用 – aaronman

+0

@aaronman同意。我認爲「淺拷貝」可以解釋這一切,不是嗎? – Mics

+0

好的,我看到了第二個答案,它現在可以工作。 –

1

Array.prototype.slice()不克隆嵌套數組。你可以做這樣的事情特別是你的問題

var array = [ 
       [ [0,1,2], [3,4,5] ] 
      ]; 

//other stuff... 

var add = array[0].slice(); //to clone the array (but not working as expected) 
add[0] = array[0][0].slice(); 
add[0][0] = 10; 
array.push(add); 

console.log(array);