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

时间:2013-03-23 04:00:53

标签: javascript jquery knockout.js

我正在使用knockout.js库。我正在尝试使用knockout arrayRemoveItem实用程序函数,但它似乎无法正常工作。这是我的代码:

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

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

1 个答案:

答案 0 :(得分:8)

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

尝试

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());

演示:Fiddle