拼接数组的Javascript只是替换值而不是删除它

Javascript splicing an array just replaces the value instead of removing it

本文关键字:删除 替换 Javascript 拼接 数组      更新时间:2023-09-26

我有一个包含菜肴列表的菜单。 我希望能够从菜单中删除菜肴,我通过在菜单数组中拼接菜肴 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()就可以工作了。

希望对您有所帮助。