javascript - 数组拼接仅适用于一个顺序

标签 javascript arrays angularjs string checkbox

我有个小问题。 我有一个用于显示 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#splicedeleteCount , 因为没有以实际索引开头的所有元素都被删除。

Parameters

deleteCount Optional

An 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. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

If deleteCount is omitted, or if its value is larger than array.length - start, then all of the elements beginning with start index on through the end of the array will be deleted.

$scope.savesGraphUserDetail.splice(index, 1);
//                                        ^

关于javascript - 数组拼接仅适用于一个顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47346287/

相关文章:

javascript - 使用 React 和一个 <div> id 的网页

javascript - 1 div 的高度取决于其他 div 的高度?

Javascript 加载/卸载以获取 PHP $_SESSION 变量

javascript - 安全地访问 Javascript 嵌套对象

php - 如何通过 php 从 mysql 获取行/数组/关联结果中的特定值检索行号?

javascript - ngStorage 在 Chrome iframe 中崩溃

javascript - JS删除数组中的多项

c++使用每个元素引用初始化数组?

javascript - 如何使用 Angular Material 日历

angularjs - 如何在 ui-select 中使用 Selectize 主题?