我有 2 个列表。
我有一个 Angular 服务,它具有基于 splice
的方法,该方法允许我通过索引根据项目的索引从第一个列表中删除项目(称为“items
”) ng-click
操作。
service.removeItem = function (itemIndex) {
items.splice(itemIndex, 1);
};
我想做的是将删除的项目添加到第二个列表(称为“购买
”),使用传递给slice
的相同索引。
我想也许我可以将此功能放入同一个函数(removeItem
)中,如下所示:
service.removeItem = function (itemIndex) {
bought.push(itemIndex);
items.splice(itemIndex, 1);
};
但是,这似乎不起作用。我尝试了一些变体(例如 bought.push(items.itemIndex)
),但没有成功。
最佳答案
使用splice
将要删除的元素插入到第二个数组中的同一索引处。
service.removeItem = function (itemIndex) {
var currItem = items[itemIndex];
// Insert the element to be removed
// at the same index in the other array
bought.splice(itemIndex, 0, currItem);
items.splice(itemIndex, 1);
};
或者不要事先访问该元素,而是使用删除该元素时返回的元素。
service.removeItem = function (itemIndex) {
var currItem = items.splice(itemIndex, 1);
bought.splice(itemIndex, 0, currItem);
};
关于javascript - 通过第一个列表中项目的索引将项目添加到第二个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39801745/