[英]Need help understanding this code snippet
Can someone please explain this snippet of code which is an angular filter with module name as ui.filters
.有人可以解释一下这段代码,它是一个角度过滤器,模块名称为ui.filters
。
angular.module('ui.filters').filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});
welcome Rajesh, here is a working plunker of the filter .欢迎拉杰什,这是过滤器的工作plunker 。
I have made some changes(correcting declaration and removing unused variable)我做了一些更改(更正声明并删除未使用的变量)
angular.module('ui.filters',[]).filter('unique', function () {
return function (items, filterOn) {
//return items as it is if the filterOn is false
if (filterOn === false) {
return items;
}
// else execute this if loop when "filterOn = defined/undefined AND items is an array"
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var newItems = [];
var extractValueToCompare = function (item) {
// checks if it item(argument) is an object AND filterOn is a string
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var isDuplicate = false;
// for first iteration of "angular.forEach" newItems is an empty array. but the value is pushed into "newItems"
// once if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) is evaluated true
for (var i = 0; i < newItems.length; i++) { // LOOP_1
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
// if not duplicate the push into newItems so that it can iterated in
// LOOP_1 defined above
if (!isDuplicate) {
newItems.push(item);
}
});
// assign unique values
items = newItems;
}
return items;
};
});
use console.log to check diffrent values in iteration使用 console.log 检查迭代中的不同值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.