Javascript引用复制问题
我有一个原始数组,初始化如下:Javascript引用复制问题,javascript,angularjs,Javascript,Angularjs,我有一个原始数组,初始化如下: $scope.rawUsers = angular.copy($scope.users); function filterUsers(searchString, onlyMine) { $scope.users = []; _.find($scope.rawUsers, function (itm) { var groups = []; if (onlyMine) { if (!itm.IsMine)
$scope.rawUsers = angular.copy($scope.users);
function filterUsers(searchString, onlyMine) {
$scope.users = [];
_.find($scope.rawUsers, function (itm) {
var groups = [];
if (onlyMine) {
if (!itm.IsMine)
return;
var hasGroup = false;
_.find(itm.Groups, function (group) {
if (lowercaseGroups.indexOf(searchString) != -1) {
hasGroup = true;
groups.push(group);
}
});
if (hasGroup) {
itm.Groups = groups;
$scope.users.push(itm);
}
} else {
if (itm.IsMine)
return;
$scope.users.push(itm);
}
});
}
然后,我修改了中的一些数据,如下所示:
$scope.rawUsers = angular.copy($scope.users);
function filterUsers(searchString, onlyMine) {
$scope.users = [];
_.find($scope.rawUsers, function (itm) {
var groups = [];
if (onlyMine) {
if (!itm.IsMine)
return;
var hasGroup = false;
_.find(itm.Groups, function (group) {
if (lowercaseGroups.indexOf(searchString) != -1) {
hasGroup = true;
groups.push(group);
}
});
if (hasGroup) {
itm.Groups = groups;
$scope.users.push(itm);
}
} else {
if (itm.IsMine)
return;
$scope.users.push(itm);
}
});
}
如何修复它以使原始值不丢失?您可以使用扩展语法
$scope.rawUsers = [...$scope.users];
这将为您提供数组$scope.users
的新副本,无需任何引用
扩展语法允许在预期零个或多个参数(用于函数调用)或元素(用于数组文字)的位置展开iterable,例如数组表达式或字符串,或者在预期零个或多个键值对(用于对象文字)的位置展开object表达式
如需进一步阅读,请访问
如果您想使用angularjs
函数,那么您可以使用angular.copy()
,因为它创建了源的深度副本,应该是一个对象或数组。这就像:
$scope.rawUsers = angular.copy($scope.users);
考虑使用角。拷贝:$Sop.RaWueS=角。拷贝($范围。用户);我正在尝试angular.copy,但它不起作用,它仍然会更新主对象中的组。我已经编辑了代码,并在使用var data=angular.copy($scope.rawUsers)时显示了更多我正在做的事情;在函数内部,然后它works@mohsinali1317然后在函数内部使用。那有什么问题?