以下是我执行此简单任务的javascript代码:
添加元素(如果元素不在数组中)。
if(_.contains(this.types,type_id)){
var index = this.types.indexOf(type_id);
this.types.splice(index,1);
}
else{
this.types.push(type_id);
}
有更有效的方法吗?
答案 0 :(得分:33)
你可以在没有第三方库的情况下做到这一点,这样会更有效率。 (这只会在找到时删除值的第一个实例,而不是多个)
的Javascript
var a = [0, 1, 2, 3, 4, 6, 7, 8, 9],
b = 5,
c = 6;
function addOrRemove(array, value) {
var index = array.indexOf(value);
if (index === -1) {
array.push(value);
} else {
array.splice(index, 1);
}
}
console.log(a);
addOrRemove(a, b);
console.log(a);
addOrRemove(a, c);
console.log(a);
输出
[0, 1, 2, 3, 4, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 6, 7, 8, 9, 5]
[0, 1, 2, 3, 4, 7, 8, 9, 5]
上
答案 1 :(得分:22)
您可以使用lodash功能" xor":
_.xor([2, 1], [2, 3]);
// => [1, 3]
如果你没有数组作为第二个参数,你可以简单地将变量包装成一个数组
var variableToInsertOrRemove = 2;
_.xor([2, 1], [variableToInsertOrRemove]);
// => [1]
_.xor([1, 3], [variableToInsertOrRemove]);
// => [1, 2, 3]
答案 2 :(得分:15)
如果你关心效率,那么可能使用数组来实现一个集合是一个坏主意。例如,使用您可以执行的对象:
function toggle(S, x) {
S[x] = 1 - (S[x]|0);
}
然后在许多添加/删除操作之后,您只能保留值为1的键
这样每次添加/删除都是O(1)
,您只需要一次O(n)
操作即可获得最终结果。
如果键都是“小”数字可能是位掩码甚至值得努力(未经测试)
function toggle(S, x) {
var i = x >> 4;
S[i] = (S[i]|0) ^ (1<<(x&15));
}
答案 3 :(得分:6)
对于不可变状态(克隆数组):
const addOrRemove = (arr, item) => arr.includes(item) ? arr.filter(i => i !== item) : [ ...arr, item ];
答案 4 :(得分:4)
查看类似问题的 this answer 。
<强>代码:强>
function toggle(collection, item) {
var idx = collection.indexOf(item);
if(idx !== -1) {
collection.splice(idx, 1);
} else {
collection.push(item);
}
}
答案 5 :(得分:1)
使用underscorejs
function toggle(a,b)
{
return _.indexOf(a,b)==-1?_.union(a,[b]):_.without(a,b);
}
用法:
var a = [1,2,3];
var b = [4];
a = toggle(a,b); // [1,2,3,4]
a = toggle(a,b); // [1,2,3]
答案 6 :(得分:0)
如果“类型”可以是Set,则
let toggle = type_id => this.types.delete(type_id) || this.types.add(type_id);
答案 7 :(得分:0)
扩展Xotic750's answer,将始终确保切换的元素在数组中仅出现一次。如果您的数组像用户输入一样是随机的,则可以使用此选项。
function toggleValueInArray(array, value) {
var index = array.indexOf(value);
if (index == -1) {
array.push(value);
} else {
do {
array.splice(index, 1);
index = array.indexOf(value);
} while (index != -1);
}
}
var a = [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9],
b = 5,
c = 10;
// toString just for good output
console.log(a.toString());
toggleValueInArray(a, b);
console.log(a.toString());
toggleValueInArray(a, c);
console.log(a.toString());