我想在對象內創建私有數組。問題是我用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();
感謝您的幫助,
問候,
安德魯
可能重複[是否有克隆jQuery中的陣列的方法?(http://stackoverflow.com/questions/3775480/is-there-a - 方法 - 克隆 - 數組在jquery) – Denis
可能重複[在javascript中按值複製數組](http://stackoverflow.com/questions/7486085/copying-array-by-value-in- javascript) – Barmar