简体   繁体   English

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

[英]How to remove item from array knockout

I am using knockout.js library. 我正在使用knockout.js库。 I am trying to using knockout arrayRemoveItem utility function but it seems that its not working. 我正在尝试使用knockout arrayRemoveItem实用程序函数,但它似乎无法正常工作。 Here is my code : 这是我的代码:

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. 如果在按下删除按钮后检查控制台,则第3项不会从阵列中删除。 What i am missing here? 我在这里缺少什么?

The arrayRemoveItem takes 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 . arrayRemoveItem将要删除的项作为第二个参数,如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 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM