代码之家  ›  专栏  ›  技术社区  ›  code.cycling

Angularjs获取数组的索引始终返回-1

  •  1
  • code.cycling  · 技术社区  · 8 年前

    使用拼接移除阵列中的项目时遇到问题。我似乎无法让它工作,它总是返回一个 -1 价值

    json对象

    {
    "_id": "5a61ad6fd5df1761dd2eb1f1",
    "branch": "Lucban",
    "__v": 0,
    "building": [
        {
            "name": "mhq",
            "floors": [
                "ground floor",
                "2nd floor"
            ]
        }
    ],
    "dateCreated": "2018-01-19T08:33:51.761Z"}
    

    html

    <span class="badge badge-pill badge-primary text-capitalize" ng-repeat="floor in vm.selectedItem.building[0].floors">{{floor}}
    <i class="fa fa-times-circle-o" aria-hidden="true" ng-click="vm.removeItem($index)"></i></span>
    

    控制器

    vm.removeItem = removeItem;
    function removeItem(data) { // data is $index of the object
      var index = vm.selectedItem.building[0].floors.indexOf(data); //always throwing -1
      console.log(index);
      vm.selectedItem.building[0].floors.splice(index, 1);
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Pankaj Parkar    8 年前

    您已经在传递项目的索引,无需再次查找搜索索引

    function removeItem(index) {
       if(vm.selectedItem.building[0].floors[index]){
         vm.selectedItem.building[0].floors.splice(index, 1);
       } else {
         console.log("No such element present at index "+index)
       }
    }
    

    如果应用了任何排序或筛选 floors 对象,然后将索引传递给 removeItem 不需要函数。在这种情况下,我建议您通过unique floor id,以便您可以根据该id确定集合中的项目 uniqueid .