gpt4 book ai didi

javascript - Angularjs 获取数组的 indexOf 总是返回 -1

转载 作者:行者123 更新时间:2023-11-30 11:24:53 26 4
gpt4 key购买 nike

我在使用 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);
}

最佳答案

您已经传递了一个项目的索引,您不需要再次查找搜索索引

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 确定集合中的项目。

关于javascript - Angularjs 获取数组的 indexOf 总是返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48393560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com