【问题标题】:Javascript splicing an array just replaces the value instead of removing it [duplicate]Javascript拼接数组只是替换值而不是删除它[重复]
【发布时间】:2016-03-18 00:46:17
【问题描述】:

我有一个包含菜式列表的菜单。我希望能够从菜单中删除菜肴,我通过在菜单数组中拼接菜肴 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
 }];

【问题讨论】:

  • 您能否展示一个错误的测试用例,即您传入的输入数组和ret._id?就目前而言,您的代码看起来不错(除了缺少的分号)
  • 为什么不能使用$scope.menuer 而不是将menu 作为arg 传递?它们有不同的内容吗?
  • menuService.update(menu) 里面的代码是什么,socket.syncUpdates('menu', $scope.menuer) 在做什么?如果你能分享之前和之后的价值,那就太好了。
  • menu.retter.indexOf(ret._id); 永远不会匹配。这不是您搜索对象数组的方式。
  • @JonasOlesen No, it doesn't.

标签: javascript arrays angularjs


【解决方案1】:

替换这一行:

var index = menu.retter.indexOf(ret._id);

通过这个:

var index = menu.retter.map(function(x){
    return x._id
}).indexOf(ret._id);

Array.map() 将返回一个只有_id 的映射数组,然后您的.indexOf() 就可以工作了。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2022-10-25
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多