[英]Why can't I remove item from this Array using slice or lodash remove?
Using slice (In this situation I find the correct item in the Array, attempt slice, but the Array stays exactly the same): 使用切片(在这种情况下,我在数组中找到正确的项目,尝试切片,但数组保持完全相同):
for (var i=0; i<vm.storedViews.length; i++) {
if (view_id === vm.storedViews[i].id) {
vm.storedViews.slice(i,1);
// vm.storedViews = _.remove(vm.storedViews, i);
break;
}
}
console.log('vm.storedViews',vm.storedViews);
Using _.remove
all items end up being removed from my Array: 使用_.remove
所有项目最终都会从我的数组中删除:
for (var i=0; i<vm.storedViews.length; i++) {
if (view_id === vm.storedViews[i].id) {
// vm.storedViews.slice(i,1);
vm.storedViews = _.remove(vm.storedViews, i);
break;
}
}
console.log('vm.storedViews',vm.storedViews);
Use .splice()
to modify the array. 使用.splice()
修改数组。 .slice
just returns the selected elements. .slice
只返回选中的元素。
vm.storedViews.splice(i, 1);
_.remove()
didn't work because the the second argument is not an index, it's a predicate function -- it removes all elements of the array for which the function returns a truthy value. _.remove()
不起作用,因为第二个参数不是索引,它是一个谓词函数 - 它删除了函数返回truthy值的数组的所有元素。 It looks like the closest lodash function to .splice()
is _.pullAt()
. 看起来像.splice()
最接近的lodash函数是_.pullAt()
。 It takes a list of array indexes to remove, so you can use it for your case where you just want to remove one element: 它需要删除一个数组索引列表,因此您可以将它用于您只想删除一个元素的情况:
_.pullAt(vm.storedViews, i);
Instead of your for
loop you can use _.findIndex()
: 您可以使用_.findIndex()
代替for
循环:
_.pullAt(vm.storedViews, _.findIndex(vm.storedViews, 'id', view_id));
If the IDs are unique, you can also use: 如果ID是唯一的,您还可以使用:
_.remove(vm.storedViews, 'id', view_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.