gpt4 book ai didi

javascript 向json中添加数据

转载 作者:行者123 更新时间:2023-11-30 12:55:46 25 4
gpt4 key购买 nike

我正在使用 angularJS,我是个新手。所以我在 Controller 范围内有一个变量,看起来像这样。

$scope.emptyContact = {'contact_firstname':'', 'contact_lastname':''};

我想用它来重置 newContact json,我用它来添加表单数据。但是当我这样做时:

$scope.newContact = $scope.emptyContact;

当我更改 newContact 变量中的内容时,它也会更改为 emptyContact 变量。有没有一种方法可以为 newContact 变量提供 emptyContact 中的值,而无需将它们的数据“绑定(bind)”在一起?谢谢你,丹尼尔!

最佳答案

是的。发生这种情况是因为对对象的引用保持不变

a = {};     // a will be an empty object
b = a; // b will be a (the reference is kept)
a === b // return true
b.c = 12; // set c key to b
a.c // returns 12 because b is a and c is set to a, too

d = JSON.parse(JSON.stringify(a)); // clone a
a === d // return false because d is not a
d.e = 13; // sets e key as 13
a.e // returns undefined because d is NOT a

所以,我总是更喜欢使用 obj1 = JSON.parse(JSON.stringify(obj1)) 来克隆一个对象。

您的代码变为:

$scope.newContact = JSON.parse(JSON.stringify($scope.emptyContact));

或使用 angular.copy() :

angular.copy($scope.emptyContact, $scope.newContact);

...并且您的 emptyContact 不会更改。

关于javascript 向json中添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19207945/

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