【问题标题】:javascript create object with private arrayjavascript 使用私有数组创建对象
【发布时间】:2013-10-12 06:24:21
【问题描述】:

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

感谢您的帮助,

问候,

安德鲁

【问题讨论】:

标签: javascript arrays object private splice


【解决方案1】:

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

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

【讨论】:

  • 哇,真快!!,感谢 Barmar 的回答,它工作得很好!
  • 附带说明:如果您最终将对象/其他数组放入数组并调用 slice,它将使用新数组中对象/数组的引用
  • 谢谢帕特里克,我会尽量记住这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 2015-02-25
  • 2019-04-05
  • 2015-10-18
  • 2015-03-05
  • 1970-01-01
相关资源
最近更新 更多