javascript 如何从数组淘汰赛中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15583191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:16:49  来源:igfitidea点击:

How to remove item from array knockout

javascriptjqueryknockout.js

提问by user1740381

I am using knockout.js library. I am trying to using knockout arrayRemoveItemutility function but it seems that its not working. Here is my code :

我正在使用knockout.js 库。我正在尝试使用淘汰赛arrayRemoveItem实用功能,但似乎不起作用。这是我的代码:

JS

JS

function VM()
{
  this.Items = [{id:'1', name:'A'}, 
                {id:'2', name:'B'}, 
                {id:'3', name:'C'}, 
                {id:'4', name:'D'}
               ];

  this.Delete = function(){
    console.log(this.Items);          //before removing

    ko.utils.arrayRemoveItem(this.Items, function(item){
      return item.id == '3';
    });

    console.log(this.Items);          //after removing
  };
}

Fiddle

小提琴

If you check the console after pressing delete button, item 3 is not removing from array. What i am missing here?

如果您在按下删除按钮后检查控制台,项目 3 不会从阵列中删除。我在这里缺少什么?

回答by Arun P Johny

The arrayRemoveItemtakes the items to be removed as the second argument like ko.utils.arrayRemoveItem(array, itemToRemove), so you need to first find the object and pass it to arrayRemoveItem.

ThearrayRemoveItem将要删除的项目作为第二个参数,例如ko.utils.arrayRemoveItem(array, itemToRemove),因此您需要首先找到该对象并将其传递给arrayRemoveItem.

Try

尝试

function VM()
{
  this.Items = [{id:'1', name:'A'}, 
                {id:'2', name:'B'}, 
                {id:'3', name:'C'}, 
                {id:'4', name:'D'}
               ];

  this.Delete = function(){

    var item;
    ko.utils.arrayForEach(this.Items, function(v) {
      if(v.id == '3'){
        item = v;
      }
    });

    console.log(this.Items);
    ko.utils.arrayRemoveItem(this.Items, item);
    console.log(this.Items);
  };
}

ko.applyBindings(new VM());

Demo: Fiddle

演示:小提琴