[英]Mutated Array in AngularJS Filter
我有一個包含一些條件的自定義AngularJS過濾器。 在我的else
條件下,我將值從數組中拼接出來並返回該數組。
這是我的問題:在else
條件中將值拼接出數組會改變該數組,如果之后調用if
條件,它將不再處理原始的完整數組和原始數組,而僅處理包含剩余索引的部分數組拼接。
我該如何糾正這個問題,以確保每次運行過濾器時都在處理完整的數據集? 我嘗試在else
塊中使用數組的副本(使用var newArr = items.splice(0)
),但是無論出於何種原因,問題仍然存在。
一種選擇是在else
條件下構建一個新數組,然后返回該數組,而不是破壞原始數組。 但是,由於我要處理的是復雜的多嵌套數據結構,為了簡單起見,我正在尋找一種可以刪除值的解決方案。
angular.module("app", []).
filter('department', function() {
return function(items, args) {
var filtered;
var output = [];
// return all items when 'All Departments' selected
if (args.selectedDepartment.Name == 'All Departments' && args.selectedDepartment.Id === undefined) {
return items;
}
// return orders containing products from selected department with 'Inclusive' option
if (args.selectedDepartment.Id !== undefined && !args.option) {
for (let i = 0; i < items.length; i++) {
filtered = items[i].products.filter(function(item) {
return item.Order__r.Department__r.Id == args.selectedDepartment.Id;
});
if (filtered.length >= 1) {
output.push(items[i]);
}
}
// return only products which are an exact match to the selected department with 'Exclusive' option
} else if (args.selectedDepartment.Id !== undefined && args.option) {
for (let i = 0; i < items.length; i++) {
for (let j = 0; j < items[i].products.length; j++) {
if (items[i].products[j].Order__r.Department__r.Id != args.selectedDepartment.Id) {
items[i].products.splice(j, 1);
}
}
if (items[i].products.length === 0) {
items.splice(i, 1);
}
}
return items;
}
return output;
};
})
從給定數組中刪除元素是一種變異操作。
另一種方法是實現非變異元素去除。 代替直接修改輸入數組,下面的remove函數可以返回一個包含除指定元素以外的所有元素的新數組:
function remove(array, element) {
return array.filter(e => e !== element);
}
const vowelsAndX = ["a", "e", "i", "o", "u", "x"];
const vowels = remove(vowelsAndX, "x");
vowels.toString(); // "a,e,i,o,u"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.