如果现有代码存在,则将其删除。它不会尝试记住是否已找到它,如果找不到则添加它。
为此,我将使用findIndex
:
function removeOrAdd(array, obj) {
var index = array.findIndex(el => el.name === newObject.name)
if (index === -1) {
// Not found, add it
array.push(newObject);
} else {
// Found, remove it
array.splice(index, 1);
// or create a new array instead of splicing:
//array = array.filter(function(_, i) { return i !== index);
}
}
findIndex
为每个数组项调用一个回调,直到该回调返回真实值,然后停止并返回该索引;如果回调函数从不返回真实值,findIndex
则在条目用尽时返回-1。
实时复制:
function removeOrAdd(array, obj) {
var index = array.findIndex(el => el.name === newObject.name)
if (index === -1) {
// Not found, add it
array.push(newObject);
} else {
// Found, remove it
array.splice(index, 1);
// or create a new array instead of splicing:
//array = array.filter(function(_, i) { return i !== index);
}
}
var array = [{name: "pet"}, {name: "animals"}]
var newObject = {name: "pet"}
console.log("before", array);
removeOrAdd(array, newObject); // Found, so it was removed
console.log("after1", array);
removeOrAdd(array, newObject); // Not found, so it was added
console.log("after2", array);
.as-console-wrapper {
max-height: 100% !important;
}
@Liam
some()
在这里不能工作,因为代码使用找到的索引来删除元素,即array.splice(index, 1);
您仅删除一个副本,而不删除所有匹配的对象。
@Liam Array#some早于Array#findIndex
@Paulpro-那就是我阅读问题的方式。总是有可能我读错了,但我不这么认为。
很公平; OP并未真正指定。我只是以为他尝试使用Array#filter是因为他想删除所有匹配项。只要我仅使用addOrRemove添加对象,我想就永远不会有重复项。