gpt4 book ai didi

javascript - 当改变复制变量的值时,它也在改变 angularjs 中的主变量值

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:07:25 25 4
gpt4 key购买 nike

我的情况很奇怪。我有一个对象数组,我使用 angular.forEach 来修改每个对象的价格键值,但是当我在每个对象中更改它时,它也会更改主数组对象。

看看代码,你就会明白我想说的是什么。

var option_1_val = $scope.options.option_1_val;
var option_2_val = $scope.options.option_2_val;
console.log('genies',sc.genies);

var new_arr = [];
var each ;
each = sc.genies;
angular.forEach(each,function(val,key){
var ob = {};
ob = val;

var priceA = angular.fromJson(ob.price);
console.log('price',priceA);

var option = option_1_val.replace(" ","-")+","+option_2_val.replace(" ","-");
console.log(option);

ob.price = priceA[option];

console.log(ob);
new_arr.push(ob);
});

option = 'Non-Vegetarian,' (after calculating)

sc.genies = [{"gs_id":"3","user_id":"25","service_id":"7","price":"{\"Vegetarian,Bengali\":\"200\",\"Vegetarian
,Chinese\":\"3100\",\"Vegetarian,Gujarati\":\"800\",\"Vegetarian,Italian\":\"100\",\"Vegetarian,Maharashtrian
\":\"100\",\"Vegetarian,Punjabi\":\"100\",\"Vegetarian,-South-Indian\":\"300\",\"Vegetarian,Thai\":\"100
\",\"Non-Vegetarian,Bengali\":\"1100\",\"Non-Vegetarian,Chinese\":\"3100\",\"Non-Vegetarian,Gujarati
\":\"100\",\"Non-Vegetarian,Italian\":\"100\",\"Non-Vegetarian,Maharashtrian\":\"100\",\"Non-Vegetarian
,Punjabi\":\"100\",\"Non-Vegetarian,-South-Indian\":\"80\",\"Non-Vegetarian,Thai\":\"100\",\"Jain,Bengali
\":\"2100\",\"Jain,Chinese\":\"2100\",\"Jain,Gujarati\":\"4100\",\"Jain,Italian\":\"100\",\"Jain,Maharashtrian
\":\"100\",\"Jain,Punjabi\":\"100\",\"Jain,-South-Indian\":\"800\",\"Jain,Thai\":\"100\"}","min_price"
:"80","max_price":"4100","username":"abdul quadir","email":"abdul.quadir@kiozen.com","rating":"3"}]

现在,当我重复 sc.genie 时,我已经将它放入一个已经“每个”的新变量中,然后我将每个数组的“price”键更改为未定义但奇怪 重点是当我在控制台中看到 sc.genies 中的 price 值也更改为“undefined”。嗯!

我希望你明白我的意思,请帮我看看为什么会这样。

谢谢

最佳答案

您应该使用 angular.copy 然后当每个值的变化不影响原始值时。因为 angular.copy 在没有引用的情况下在新变量中分配旧值。

喜欢:

var each ;
each = angular.copy(sc.genies);

代替

each = sc.genies;

关于javascript - 当改变复制变量的值时,它也在改变 angularjs 中的主变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078905/

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