简体   繁体   English

JavaScript:分配给数组中的对象会更改数组中所有对象的值

[英]JavaScript: assignment to an object within an array changes the value of all objects in the array

I have an object which have an array to hold all the children of this object, the children are also instances of the same object (I need this for a tree like structure where the object is a node of the tree) 我有一个对象,该对象具有一个数组来容纳该对象的所有子对象,这些子对象也是同一对象的实例(我需要一个像树一样的结构,其中该对象是树的节点)

var bugObject = function(kFlag){
  this._kFlag = kFlag; 
  this._children = []
}

bugObject.prototype.getKFlag = function(){
  return this._kFlag; 
}; 


bugObject.prototype.setChildrenFromData = function(data){

 var i = 0;
 var kFlag = {flagType : 'someFlag', flagValue : -1};
 kddFlag.flagType = data.flagType;

 var len = data.flagValues.length; 
 for( i = 0 ; i < len ; i++){
        kFlag.flagValue = data.flagValues[i];
        this._children.push(
            new bugObject(kFlag)
        );

                 //this is just to print the children 
        for(j = 0; j<=i; j++){
            console.log('child : ' + j + ' for test :' + i); 
            console.log(this._children[i].getKFlag());
        }
        console.log('--------------------');
 }

}; 

The idea is to create the children of this object based on some data using the setChildrenFromData method here is how I am doing this: 想法是使用setChildrenFromData方法基于一些数据创建此对象的子级,这是我的操作方式:

function main(){

console.log('main is called'); 
var data = {"flagType":"someFlag","flagValues":[0,0,0,0,0,0,0,0,1,0,0]}; 

var rootNode = new bugObject(null); 
rootNode.setChildrenFromData(data); 

}

main(); 

The problem is that instead of getting 11 objects each of them have one of these flags [0,0,0,0,0,0,0,0,0,0,1] I get 11 objects all of them have the flag 1, (the last one)! 问题是我没有得到11个对象,每个对象都具有以下标志之一[0,0,0,0,0,0,0,0,0,0,1,1]我得到了11个对象,所有这些对象均具有标志1,(最后一个)!

Could you please see what is wrong! 请问出什么问题了!

Thanks 谢谢

The problem is this: 问题是这样的:

for( i = 0 ; i < len ; i++){
        kddFlag.flagValue = data.flagValues[i];
        this._children.push(
            new bugObject(kddFlag)
        );

you're creating 11 bugObject . 您正在创建11 bugObject But all of them have this._kddFlag pointing to the same kddFlag object, at the end of the loop kddFlag.flagValue is 1. To fix this, move your code into the loop. 但是它们所有人都有this._kddFlag指向同一个kddFlag对象,在循环的kddFlag.flagValue为1。要解决此问题,请将代码移入循环。 Like this: 像这样:

for( i = 0 ; i < len ; i++){
           var kddFlag = {flagType : 'outlier', flagValue : -1};
            kddFlag.flagType = data.flagType;
            kddFlag.flagValue = data.flagValues[i];
            this._children.push(
               new bugObject(kddFlag)
            );

This is a problem with assigning references to objects, and is well known, and even happens in other languages. 这是将引用分配给对象的问题,这是众所周知的,甚至在其他语言中也会发生。

I'll give you a simpler example: 我给你一个简单的例子:

Let's say you want a 3x3 matrix, modelled as an array of arrays, filled with rows that are all zeros. 假设您要一个3x3矩阵,建模为一个数组数组,并填充全为零的行。

You might be tempted to write. 您可能会想写。

row = [0,0,0];
A = [];
for(j=0;j<3;++j) A[j] = row;

But then if you change A[0][0] = 10; 但是,如果您更改A[0][0] = 10;

And you look in A[1][0] , you get 10 , not 0 . 然后看A[1][0] ,得到10 ,而不是0

This is because there is only one row , and all of the elements of A are assigned to it. 这是因为只有row ,并且A所有元素都分配给它。

To correct this pattern in Javascript, the object needs to be a new object each time. 要更正Javascript中的这种模式,该对象每次都需要是一个新对象。 This can be done with a literal A[j]=[0,0,0] or it can be A[j]=row.slice() which makes a shallow copy that solves the problem for one level, or a deep copy. 可以使用文字A[j]=[0,0,0]来完成,也可以是A[j]=row.slice()进行浅层复制以解决一个级别的问题,也可以进行深层复制。

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

相关问题 数组中所有对象的 1 个对象的值变化 - Value change in 1 object changes in all objects in array Javascript:迭代嵌套在 object 中的对象数组作为值 - Javascript: Iterate over an array of objects nested within an object as a value Javascript 更改对象数组中所有项目的属性 - Javascript changes attributes in all items in array of objects javascript object 赋值一个数组 - javascript object Assignment an array 使用eslint错误更新javascript数组中所有对象的对象值 - update object value of all objects in javascript array with eslint error 检查 object 值是否存在于 Javascript 对象数组中,如果不存在,则将新的 object 添加到数组中 - Check if object value exists within a Javascript array of objects and if not add a new object to array JavaScript-将对象内的对象推送到全局数组 - JavaScript - Push objects within object to global array 过滤对象内object的数组值 - Filtering array value of object within objects Javascript:根据对象上嵌套数组中的值查找数组中对象的索引 - Javascript: Finding index of an object in an array, based on a value within a nested array on the objects 在对象数组中的属性中查找具有最大值的所有对象,并从同一对象返回其他属性的值 - Finding all objects with Max value in a property within an Array of Objects and return values of other property from the same object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM