简体   繁体   English

在引用变量中更改时原始数组未更新

[英]Original array not getting updated when changed in referenced variable

For my work, I need to access nested object array.对于我的工作,我需要访问嵌套的 object 数组。 I do not want to access it every time with full path.我不想每次都使用完整路径访问它。 So I wanted to shorten the reference by assigning the actual reference to a variable.所以我想通过将实际引用分配给变量来缩短引用。

I tried to find out existing answers, but didn't get answer for this scenario.我试图找出现有的答案,但没有得到这种情况的答案。

What I have done: Assigned the reference of array to a variable, modified the referenced value.我所做的:将数组的引用分配给变量,修改引用的值。 But the original array is not getting modified.但是原始数组没有被修改。

Below is a demo code for what I want to achieve.下面是我想要实现的演示代码。

 let obj = { innerObj1: { arr: [2,3,4,5,6] } } var ref = obj.innerObj1.arr; console.log(ref); // output [2,3,4,5,6] ref = ref.filter(n => n%2 == 0); console.log(ref); // output [2,4,6] //Original obj console.log(obj.innerObj1.arr) // output [2,3,4,5,6]

Just access specific indices within ref :只需访问ref中的特定索引:

let obj = {
    innerObj1: {
        arr: [2, 3, 4, 5, 6]
    }
}

const ref = obj.innerObj1.arr;
console.log(ref);
// output [2, 3, 4, 5, 6]

for(let i = 0; i < ref.length; i++) {
  ref[i] = ref[i] % 2 == 0;
}

// Original obj
console.log(obj.innerObj1.arr)
// output [true, false, true, false, true]

when we do当我们这样做时

var ref = obj.innerObj1.arr;

we are having a pointer to obj.innerObj1.arr ref is reference to array when we do ref.filter(n => n%2 == 0);当我们执行ref.filter(n => n%2 == 0);时,我们有一个指向obj.innerObj1.arr的指针是对数组的ref

to get what we want we have to do为了得到我们想要的,我们必须做

obj.innerObj1.arr = ref.filter(n => n%2 == 0);

This is because filter method returns a new array and you are overriding it with the new value.这是因为filter方法返回一个新数组,而您正在用新值覆盖它。

As stated earlier it creates a new array, it means ref variable is not referring to old array anymore.如前所述,它创建了一个新数组,这意味着ref变量不再引用旧数组。 It is referring to new array created by filter method.它指的是通过filter方法创建的新数组。

You can simply use for, while or do while loop to resolve your this issue.您可以简单地使用 for、while 或 do while 循环来解决此问题。

I hope it will help you.我希望它会帮助你。 Please find working example here:请在此处找到工作示例:

 let obj = { innerObj1: { arr: [2,3,4,5,6] } } var ref = obj.innerObj1.arr; console.log(ref); // output [2,3,4,5,6] for(let index=0; index < ref.length; index++) { if(ref[index] % 2 === 0) { ref[index] = ref[index] } else{ ref.splice(index,1); } } console.log(ref); // output [2,4,6] //Original obj console.log(obj.innerObj1.arr) // output [2,3,4,5,6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM