我正在寻找更优雅、更有效的方式来切换数组中的对象。
所以我的arr是:
let arr = [
{id: 2},
{id: 3},
...
]
现在我这样做:
if (arr.find(function(element) { return element.id === upload.id } )) {
arr = arr.filter(function(element) {
return element.id !== upload.id;
});
}
else {
arr.push(upload)
}
最佳答案
const index = arr.findIndex(function(element) { return element.id === upload.id });
if (index > -1) {
arr.splice(index, 1);
}) else {
arr.push(upload);
}
关于javascript - 如果对象在 JS 数组中,则从数组中推送或删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006466/