需要帮助理解此代码段

时间:2017-01-02 07:43:52

标签: angularjs

有人可以解释这段代码片段,它是一个角色过滤器,模块名称为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;
  };
});

1 个答案:

答案 0 :(得分:1)

欢迎Rajesh,here is a working plunker of the filter

我做了一些更改(更正声明和删除未使用的变量)

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;
  };
});

使用console.log检查迭代中的不同值