我想在对象中创建一个私有数组。问题是我正在使用 arrCopy 复制 obj.arr,但它似乎只引用了 obj.arr。当我拼接它时,这会导致问题,因为它会影响 obj.arr,在代码的任何进一步运行中都会更短。
这是一个带有代码示例的代码笔。
这是关注的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();
谢谢你的帮助,
问候,
安德鲁