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

how to push elements to an array without repeating non of them?

本文关键字:数组 元素 情况下      更新时间:2023-09-26

我在这里录制了一段视频,让您更容易理解这个问题。正如你所看到的,我正在从一个数组中选择一些元素,并将这些元素推送到另一个名为$scope.favoriteLeague = [];的数组中,以便创建一个最喜欢的联赛列表,在该视频中,我可以随心所欲地推送该元素,但我不希望这样,我希望每个元素都只能选择一次列表中的元素,如果用户试图选择一个已经在最喜欢的数组中的元素,然后显示一条消息。

我使用的是lodashangular,这是代码:

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

html

<ion-item ng-repeat="league in favoriteLeague">
    {{league.name}}
</ion-item>

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

$scope.addToFavorites = function(league) {
    if ($scope.favoriteLeague.indexOf(league) === -1){
        $scope.favoriteLeague.push(league);
    }
};

.indexOf()方法可能是您想要的。将其封装在调用addToFavorites的代码中(这样,如果值已经存在,则甚至不调用该函数):

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

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

事实上,我有自己的解决方案基于@itcouldbeaboat回答

$scope.addToFavorites = function(league) {
  if ($scope.favoriteLeague.indexOf(league) === -1) {
    $scope.favoriteLeague.push(league);
  }else {
    console.log('already exists!!!!!');
  }
};

在推送数组之前,只需检查数组是否包含联盟即可。

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