我想在对象中创建一个私有数组。问题是我用arrCopy复制obj.arr但似乎只引用了obj.arr。当我将它拼接时会导致问题,因为它会影响obj.arr,在任何进一步的代码运行时它会更短。
这里是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 :(得分:3)
当您在Javascript中分配对象或数组时,它只是复制对原始数组或对象的引用,它不会复制内容。要制作数组的副本,请使用:
var arrCopy = this.arr.slice(0);