当我更新索引0处的对象时,Javascript数组包含相同的对象倍数,它会自动更新索引1处的对象吗?

时间:2015-12-17 08:01:19

标签: javascript arrays angularjs

you can see that the rule counter propert in object being inserted is 1 and in the array we can see that the ruleCounter property has value 1

Then i try to insert same object but this time ruleCounter has a value of 2 but magically in the array you can see that the value of ruleCounter in bot objects in the array becomes 2

您可以看到正在插入的对象中的ruleCounter属性为1  在数组中插入后,我们可以看到ruleCounter属性的值为1 然后我尝试插入相同的对象,但这次ruleCounter的值为2,但神奇地在数组中你可以看到数组中两个对象中的ruleCounter的值变为2

请帮助为什么在数组的不同索引中ruleCounter的值会自动更新

var droppedObjects = []; //this array will contain the list of rules dropped on the drop zone area.
    $scope.onDropComplete1 = function(data, evt) {
        ruleCounter++;
        data.ruleCounter= ruleCounter;
        console.log(data);
        //var index = $scope.droppedObjects.indexOf(data);
        if (data !== null) {
            droppedObjects.push(data); //droping data into the array when drag and drop is complete
            console.log(droppedObjects);
        } else {
            //console.log($scope.droppedObjects1);
        }

    };

1 个答案:

答案 0 :(得分:1)

在javascript中,复杂对象通过引用传递。这意味着如果你有:

var objectA = {/* your properties */};
var objectB = objectA;

两个变量都包含对同一对象的引用。因此,如果使用任何这些变量更改属性,则同时更改另一个变量中的值。 如果要保持不同的状态,则需要创建对象的副本。

var objectA = {/* your properties */};
var objectB = new Object(objectA); // or Object.create(objectA)

现在两者都是不同的对象,您可以单独更改其属性。