2013-10-05 88 views
0

我想在對象內創建私有數組。問題是我用arrCopy複製obj.arr,但它似乎只引用obj.arr。當我拼接它時,這會引起問題,因爲它會影響obj.arr,而在代碼的任何進一步運行中它將會更短。javascript創建私有數組對象

這裏是a codepen與一個代碼玩的例子。

這裏是一個令人關注的JavaScript的

var obj = { 
    min: 3, 
    max: 9, 
    // I want the array to be private and never to change. 
    arr : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 
    inside: function(){ 
    // I want this variable to copy the arrays values into a new array that can be modified with splice() 
    var arrCopy = this.arr; 
     console.log('obj.arr: ' + this.arr); 
     console.log('arrCopy: ' + arrCopy); 
    // I want to be able to splice arrCopy without affecting obj.arr so next time the function is run it gets the value of obj.arr again 
    var arrSplit = arrCopy.splice(arrCopy.indexOf(this.min), (arrCopy.indexOf(this.max) - arrCopy.indexOf(this.min) + 1)); 
    console.log('arrSplit: ' + arrSplit); 
    console.log('obj.arr: ' + this.arr); 
    } 
} 

//to run un-comment the next line 
//obj.inside(); 

感謝您的幫助,

問候,

安德魯

+0

可能重複[是否有克隆jQuery中的陣列的方法?(http://stackoverflow.com/questions/3775480/is-there-a - 方法 - 克隆 - 數組在jquery) – Denis

+0

可能重複[在javascript中按值複製數組](http://stackoverflow.com/questions/7486085/copying-array-by-value-in- javascript) – Barmar

回答

3

當分配的JavaScript對象或數組,它只是份參考原始數組或對象,它不復制內容。爲了使一個數組的副本,請使用:

var arrCopy = this.arr.slice(0); 
+0

**哇,這很快!! **,謝謝你的答案Barmar它完美的工作! – synthet1c

+1

作爲一個旁註:如果您最終將對象/其他數組放入數組並調用切片,它將使用新數組中對象/數組的引用 –

+0

謝謝Patrick I將嘗試牢記這一點未來。 – synthet1c