JavaScript 创建带有私有数组的对象



我想在一个对象中创建一个私有数组。问题是我正在使用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();

感谢您的任何帮助,

问候

安德鲁

当你在Javascript中分配对象或数组时,它只是复制对原始数组或对象的引用,它不会复制内容。要创建数组的副本,请使用:

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

最新更新