我有个小问题。 我有一个用于显示 div 的复选框。我可以从 6 个不同的复选框中选择要显示的 div。
当检查复选框时,我会显示DIV并发送到DIV的服务器。
$scope.savesGraphUserDetail = [];
$scope.addRemoveUserChart = function(checked, value) {
if (checked) {
$scope.savesGraphUserDetail.push(value);
var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
var data = {graphsConfig: $scope.savesGraphUserDetail};
$http
.post(serviceBase + "blabla", data, config)
.success(function(data, status, headers, config) {
})
.error(function(data, status, header, config) {
});
}else {
var index = $scope.savesGraphUserDetail.indexOf(value);
$scope.savesGraphUserDetail.splice(index);
var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
var data = {graphsConfig: $scope.savesGraphUserDetail};
$http
.post(serviceBase + "blabla", data, config)
.success(function(data, status, headers, config) {
})
.error(function(data, status, header, config) {
});
}
这没关系, 但是当我取消选中复选框时,我遇到了问题,因为如果我按此顺序检查 第一次点击“A”,第二次点击“C”,第三次点击“D”,我像这样插入我的数组
myArray = ["A", "C", "D"]
如果我以相反的顺序取消选中, 首先取消选中“D”
myArray = ["A", "C"]
第二次取消选中“C”
myArray = ["A"]
最后一个“A”
myArray = []
这很完美,但是如果我在取消选中复选框时更改顺序
myArray = ["A", "C", "D"]
如果我先取消选中“C”,我的数组会删除“C”和“D”,我会得到这个
myArray = ["A"]
如果我先取消选中“A”,我的数组会删除“A”、“C”和“D”,我会得到这个
myArray = []
如何删除唯一未选中的项目?
最佳答案
您需要指定Array#splice
的deleteCount
, 因为没有以实际索引开头的所有元素都被删除。
Parameters
deleteCount
OptionalAn integer indicating the number of old array elements to remove. If
deleteCount
is 0, no elements are removed. In this case, you should specify at least one new element. IfdeleteCount
is greater than the number of elements left in the array starting atstart
, then all of the elements through the end of the array will be deleted.If
deleteCount
is omitted, or if its value is larger thanarray.length - start
, then all of the elements beginning withstart
index on through the end of the array will be deleted.
$scope.savesGraphUserDetail.splice(index, 1);
// ^
关于javascript - 数组拼接仅适用于一个顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47346287/