我有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>
最佳答案
您应该检查它是否不在数组中。 @itcouldevenbeaboat 很接近,但它应该是 === -1
而不是 !== -1
$scope.addToFavorites = function(league) {
if ($scope.favoriteLeague.indexOf(league) === -1){
$scope.favoriteLeague.push(league);
}
};
关于javascript - 如何将元素插入数组而不重复它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28435658/