代码之家  ›  专栏  ›  技术社区  ›  Non

如何在不重复非元素的情况下将元素推送到数组中?

  •  1
  • Non  · 技术社区  · 11 年前

    我有 this issue here recorded on a video 让你更容易理解。如您所见,我正在从一个数组中选择一些元素,并将这些元素推送到另一个名为 $scope.favoriteLeague = []; 为了制作一个最喜爱的联赛列表,在那个视频中,我将元素按我想要的次数推送,但我不想这样做,我希望每个元素只能在列表中选择一次,如果用户尝试选择已经在最喜爱的数组中的元素,则会显示一条消息。

    我正在使用 lodash angular ,这是代码:

    $scope.favoriteLeague = []; 
    
    $scope.addToFavorites = function(league) {
    
       $scope.favoriteLeague.push(league);
    
    };
    

    html格式

    <ion-item ng-repeat="league in favoriteLeague">
    
        {{league.name}}
    
    </ion-item>
    
    4 回复  |  直到 11 年前
        1
  •  4
  •   Charlie    11 年前

    您应该检查它是否不在数组中@甚至可能是因为船很近,但它应该是 === -1 而不是 !== -1

    $scope.addToFavorites = function(league) {
    
        if ($scope.favoriteLeague.indexOf(league) === -1){
            $scope.favoriteLeague.push(league);
        }
    
    };
    
        2
  •  1
  •   talemyn    11 年前

    这个 .indexOf() 方法是您可能正在寻找的。在代码中包含以下内容 addToFavorites 被调用(这样,如果值已经存在,您甚至不调用函数):

    if ($scope.favoriteLeague.indexOf(league) === -1) {
    
        . . . your existing call to addToFavorites . . .
    
    }
    

    或者,如果使用jQuery,可以使用 $.inArray() 方法来做同样的事情。

        3
  •  1
  •   Non    11 年前

    事实上,我得到了自己的解决方案,它甚至可以是答案

    $scope.addToFavorites = function(league) {
      if ($scope.favoriteLeague.indexOf(league) === -1) {
        $scope.favoriteLeague.push(league);
      }else {
        console.log('already exists!!!!!');
      }
    };
    
        4
  •  0
  •   Code Whisperer    11 年前

    在推进之前,只需检查阵列是否包含联盟。

    $scope.addToFavorites = function(league) {
    
        $scope.favoriteLeague.indexOf(league) === -1 ? $scope.favoriteLeague.push(league) : void 0;
    
    };