当单选按钮改变时,如何避免重复值被推入数组?
如果我将单选按钮值更改为其他单选按钮值,则先前选择的值将推入数组
我的代码
$scope.toggleSelection = function(clickedItem) {
//console.log(clickedItem)
var value = clickedItem;
var index = $scope.selected_ingrediants.indexOf(value);
if (index === -1) {
$scope.selected_ingrediants.push(value);
} else {
$scope.selected_ingrediants.splice(index, 1);
}
}
答案 0 :(得分:1)
这可能更简单:
if (!$scope.selected_ingrediants.includes(value)) {
$scope.selected_ingrediants.push(value);
}
只是要添加,@ alexandru的评论是有效的,它应该按原样运作。
答案 1 :(得分:0)
Underscore js可以帮助您轻松
var arr = [4,16,9,12,3,4,6,16,9];
var arrayWithUniqueValues = [];
_.each(arr,function(item){
if(!_.contains(arrayWithUniqueValues,item)){
arrayWithUniqueValues.push(item);
}
});
console.log(arrayWithUniqueValues) //returns [4,16,9,12,3,6]
//For your Example
$scope.toggleSelection = function(clickedItem) {
_.contains($scope.selected_ingrediants,clickedItem) ?
$scope.selected_ingrediants.splice(index, 1) :
$scope.selected_ingrediants.push(value);
}