我有一个包含菜肴列表的菜单。我希望能够从菜单中删除菜肴,我通过在菜单数组中拼接菜肴 ID 的索引来实现此目的。 但它并没有删除该值并缩短数组,而是只是用数组中的最后一个值替换该值。
在一个有 4 个菜品的菜单中,删除其中 3 个菜品后,数组仍然包含 4 个值,它们都是相同的。
$scope.fjernRet = function(ret, menu) {
//console.log(ret._id)
var index = menu.retter.indexOf(ret._id);
if (index > -1) {
menu.retter.splice(index, 1)
}
menuService.update(menu);
socket.syncUpdates('menu', $scope.menuer);
}
menu.retter
可能看起来像
[{
_id: '56e827ba0ec7a8d02bf7747d',
name: 'test',
info: 'testinfo',
type: 'kød',
active: true
}, {
_id: '56e827ba0ec7a8d02bf77473',
name: 'test3',
info: 'testinfo3',
type: 'kød',
active: true
}, {
_id: '56e827ba0ec7a8d02bf77474',
name: 'test4',
info: 'testinfo4',
type: 'salat',
active: false
}];
最佳答案
替换这一行:
var index = menu.retter.indexOf(ret._id);
通过这个:
var index = menu.retter.map(function(x){
return x._id
}).indexOf(ret._id);
Array.map()
将返回一个仅包含 _id
的映射数组,然后您的 .indexOf()
就可以工作。
希望有帮助。
关于Javascript 拼接数组只是替换值而不是删除它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066034/