gpt4 book ai didi

javascript - 如何从数组 knockout 中删除项目

转载 作者:行者123 更新时间:2023-12-01 02:21:48 24 4
gpt4 key购买 nike

我正在使用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 项并未从阵列中删除。我在这里缺少什么?

最佳答案

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

关于javascript - 如何从数组 knockout 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15583191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com