我在使用splice删除数组中的项目时遇到问题。我似乎无法使其工作,它始终返回-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);
}
答案 0 :(得分:3)
您已经传递了某个项目的索引,您不需要再次搜索索引
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
函数。在这种情况下,我建议您传递唯一的floor
ID,以便您可以根据uniqueid
确定收藏中的哪个项目。