我有一个动态数组。值来自方法推送的函数,我希望能够检查数组是否已经包含具有相同字母的元素“X”,所以我想删除该元素然后推送新元素。我怎样才能做到这一点? 这是 plunker 用我的代码
代码
$scope.selectedCat = [];
$scope.selectedCl = [];
$scope.updateCategory = function (categoryId) {
if ($scope.selectedCat.indexOf(categoryId) > -1) {
$scope.selectedCat.splice($scope.selectedCat.indexOf(categoryId), 1);
} else {
$scope.selectedCat.push(categoryId);
}
$scope.queryCategory = 'categoryId=in=(' + $scope.selectedCat + ")"
// console.log($scope.queryCategory)
//Optional, to reload on change.
$scope.requestSelected ($scope.queryCategory)
};
$scope.updateClass = function (classId) {
if ($scope.selectedCl.indexOf(classId) > -1) {
$scope.selectedCl.splice($scope.selectedCl.indexOf(classId), 1);
} else {
$scope.selectedCl.push(classId);
}
$scope.queryClass = 'eventClassId=in=(' + $scope.selectedCl + ")"
// console.log($scope.queryClass)
//Optional, to reload on change.
$scope.requestSelected ($scope.queryClass)
};
$scope.filter = []
var string;
$scope.requestSelected = function (param){
if($scope.filter already has an elem with the same letters as param){
// delete this elem then
$scope.filter.push(param)
} else {
$scope.filter.push(param)
}
// final result
string = $scope.filter.join(";")
console.log(string)
}
已更新 在@Anton 的帮助下,我终于完成了创建正确请求的逻辑。这是工作 plunker .也许对某人有用
最佳答案
您总是在此处添加条件 $scope.filter.push(param)
,而不是您必须为每个搜索字段分隔不同的字段并执行如下操作:
var filterOptions = {
filterBy: '&$filter=',
filterParam: "",
classId: '',
categoryId: ''
};
$scope.selectedCat = [];
$scope.selectedCl = [];
$scope.updateCategory = function (categoryId) {
if ($scope.selectedCat.indexOf(categoryId) > -1) {
$scope.selectedCat.splice($scope.selectedCat.indexOf(categoryId), 1);
} else {
$scope.selectedCat.push(categoryId);
}
filterOptions.categoryId = 'categoryId=in=(' + $scope.selectedCat + ")"
filterOptions.filterParam = filterOptions.classId + ";" + filterOptions.categoryId
console.log(filterOptions.filterParam)
};
$scope.updateClass = function (classId) {
if ($scope.selectedCl.indexOf(classId) > -1) {
$scope.selectedCl.splice($scope.selectedCl.indexOf(classId), 1);
} else {
$scope.selectedCl.push(classId);
}
filterOptions.classId = 'eventClassId=in=(' + $scope.selectedCl + ")"
filterOptions.filterParam = filterOptions.classId + ";" + filterOptions.categoryId
console.log(filterOptions.filterParam)
};
关于javascript - 按首字母从数组中查找和删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39048406/