gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:33:33 25 4
gpt4 key购买 nike

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);
}

};

最佳答案

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

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

两个变量都保存对同一对象的引用。因此,如果您在使用任何这些变量时更改属性,您就会同时更改另一个变量中的值。如果您想保留不同的状态,您将需要创建该对象的副本。

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

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

关于当我更新索引 0 处的对象时,Javascript 数组多次包含相同的对象,它会自动更新索引 1 处的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34329428/

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