Javascript 常量数组更改
我在Javascript 常量数组更改,javascript,Javascript,我在tempoccuppiedmonths this.occupiedMonths = []; for (let index = 0; index < this.startMonth; index++){ this.occupiedMonths.push(index) } for (let index = this.endMonth+1; index<=34; index++){ this.occupiedMonths.push
tempoccuppiedmonths
this.occupiedMonths = [];
for (let index = 0; index < this.startMonth; index++){
this.occupiedMonths.push(index)
}
for (let index = this.endMonth+1; index<=34; index++){
this.occupiedMonths.push(index)
}
const tempOccupiedMonths = this.occupiedMonths
然后
我预计tempOccupiedMonths仍然是[3,4,5,…,34],但tempOccupiedMonths=this.occupiedMonths=[0,1,2,…,34]。这是为什么?我是如何解决这个问题的。谢谢将一个数组引用分配给另一个变量将使两个变量指向同一个数组,即数组的修改由两个变量反映。您可以使用
slice
创建数组的浅拷贝
const tempOccupiedMonths = this.occupiedMonths.slice();
不要直接将数组赋值为tempOccupiedMonths=this.occupiedMonths=[3,4,5,…,34],因为它们正在引用。无参考的等面积,请遵循以下步骤。我们正在使用扩展运算符[…this.occupiedMonths] 排列运算符:
让firstArray=[];
设secondArray=[];
firstArray=secondArray=[3,4,5];
log(`firstArray:${firstArray}`);//第一阵列:3,4,5
log(`secondArray:${secondArray}`);//第二个数组:3,4,5
firstArray.push(1,2,3);
log(`firstArray:${firstArray}`);//第一个数组:3,4,5,1,2,3
log(`secondArray:${secondArray}`);//第二个数组:3,4,5,1,2,3
// ========================================
secondArray=[3,4,5];
firstArray=[…secondArray];
log(`firstArray:${firstArray}`);//第一阵列:3,4,5
log(`secondArray:${secondArray}`);//第二个数组:3,4,5
firstArray.push(1,2,3);
log(`firstArray:${firstArray}`);//第一个数组:3,4,5,1,2,3
log(`secondArray:${secondArray}`);//第二个数组:3,4,5您正在执行此.occupiedMonths的浅拷贝,而不是此.occupiedMonths的深拷贝,因此this.occupiedMonths和tempocupiedmonths在内存中共享相同的地址
试试这个
const tempOccupiedMonths=[...this.occupiedMonths]
希望对你有帮助
有关jsspread syntax
的详细信息,请遵循此操作将数组引用从一个变量分配到另一个变量不会复制数组。我现在就知道了。非常感谢。
const tempOccupiedMonths = this.occupiedMonths.slice();
const tempOccupiedMonths=[...this.occupiedMonths]