gpt4 book ai didi

javascript 使用私有(private)数组创建对象

转载 作者:行者123 更新时间:2023-11-28 20:15:53 25 4
gpt4 key购买 nike

我想在对象内创建一个私有(private)数组。问题是我正在用 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中分配对象或数组时,它只是复制对原始数组或对象的引用,而不复制内容。要制作数组的副本,请使用:

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

关于javascript 使用私有(private)数组创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com