我如何使用AngulsJS函数来简化for循环?



我有以下循环,想知道在AngularJS中是否有更有效的方法来做到这一点。所以我想循环遍历ListA中的每个项目,如果它不存在于ListB中,那么我想将项目从ListA推入ListB。但破裂;停止循环,它不会遍历ListA

中的所有项
for (item of $scope.ListA) {
let found = false;
for (obj of $scope.ListB) {
if (obj.Name == item.Name
&& obj.Field == item.Field
&& obj.DisplayName == item.DisplayName)
{
found = true;
//       console.log("double found !");
break;
}
}
if (!found)
$scope.ListB.push(newObj);
}

如何使用AngularJS函数来实现这个?

我不知道是否有任何特定的angularjs功能,但假设ListAListB只是javascript数组,你可以使用标准的数组方法来简化你的解决方案。

例如,这里我使用array.filter,array.some...扩散运算符:

// Scope example
const $scope = {
ListA: [
{ Name: 'name1', Field: 'field1', DisplayName: 'displayName1' },
{ Name: 'name2', Field: 'field2', DisplayName: 'displayName2' },
{ Name: 'name3', Field: 'field3', DisplayName: 'displayName3' },
],
ListB: [
{ Name: 'name2', Field: 'field2', DisplayName: 'displayName2' },
{ Name: 'name4', Field: 'field4', DisplayName: 'displayName4' },
],
};
// A function that checks if a list contains an item
const hasItemInList = (item, list) => {
// Here we use "array.some" method, which returns "true" if condition is true for any of the array items
return list.some(listItem => 
listItem.Name == item.Name &&
listItem.Field == item.Field &&
listItem.DisplayName == item.DisplayName
);
}
// Getting the array of items that should be added to the listB,
// Here we use "array.filter" to filter the items of array by provided condition
const itemsToAdd = $scope.ListA.filter(item => !hasItemInList(item, $scope.ListB));
// And here we push all the items to the listB,
// we use a spread operator "..." here to push all the items of array at once
$scope.ListB.push(...itemsToAdd);
console.log($scope.ListB);

数组方法- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

相关内容

  • 没有找到相关文章

最新更新