我處於一個奇怪的狀態。我有一個對象數組,我使用angular.forEach來修改每個對象的價格鍵值,但是當我每次更改它時,它也會更改主數組對象。當改變複製變量的值時,它也會改變angularjs中的主變量值
看看代碼,你會明白我想說什麼。
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":"[email protected]","rating":"3"}]
現在,當我重複sc.genie,我已經在一個新的變量已經「每一個」,然後我改變它採取「價格」每個數組未定義的關鍵,但奇怪的點是當我看到在sc.genies中的控制檯價格價格也變爲「未定義」。咦!
我希望你明白我的觀點,請幫助我爲什麼會發生這種情況。
感謝
每個都和sc.genies是指相同的對象。通過'var each = angular.copy(sc.genies);'創建一個副本,然後對'each'對象做任何你想做的事情,而不影響'sc.genies'。 – Lokesh
這可以從var ob = {}縮短; ob = val;'到'var ob = val;'。沒有必要申報這個變量,然後立即將它覆蓋... –