如何使用JavaScript切换数组中的元素?

wwl*_*wli 32 javascript arrays toggle underscore.js

这是我为这个简单任务的javascript代码:

  1. 如果元素存在于数组中,请将其删除.
  2. 如果元素不在数组中,请添加元素.

    if(_.contains(this.types,type_id)){
        var index = this.types.indexOf(type_id);
        this.types.splice(index,1);
    }
    else{
        this.types.push(type_id);
    }
    
    Run Code Online (Sandbox Code Playgroud)

有没有更有效的方法来做到这一点?

Xot*_*750 34

你可以在没有第三方库的情况下做到这一点,这样会更有效率.(这只会删除找到的第一个值,而不是多个)

使用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);
Run Code Online (Sandbox Code Playgroud)

产量

[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] 
Run Code Online (Sandbox Code Playgroud)

jsfiddle


Dav*_*nni 27

你可以使用lodash函数"xor":

_.xor([2, 1], [2, 3]);
// => [1, 3]
Run Code Online (Sandbox Code Playgroud)

如果你没有数组作为第二个参数,你可以简单地将变量包装成一个数组

var variableToInsertOrRemove = 2;
_.xor([2, 1], [variableToInsertOrRemove]);
// => [1]
_.xor([1, 3], [variableToInsertOrRemove]);
// => [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

这是doc:https://lodash.com/docs/4.16.4#xor

  • 请注意,这会返回一个新数组,而不是修改原始数组。 (2认同)

650*_*502 16

如果你关心效率,那么可能使用数组来实现一个集合是一个坏主意.例如,使用您可以执行的对象:

function toggle(S, x) {
    S[x] = 1 - (S[x]|0);
}
Run Code Online (Sandbox Code Playgroud)

然后在许多添加/删除操作之后,您只能保留值为1的键

这样每次添加/删除O(1)都只需要一次O(n)操作即可获得最终结果.

如果键都是"小"数字可能是位掩码甚至值得努力(未测试)

function toggle(S, x) {
    var i = x >> 4;
    S[i] = (S[i]|0) ^ (1<<(x&15));
}
Run Code Online (Sandbox Code Playgroud)


Yai*_*wil 8

对于不可变状态(克隆数组):

const addOrRemove = (arr, item) => arr.includes(item) ? arr.filter(i => i !== item) : [ ...arr, item ];
Run Code Online (Sandbox Code Playgroud)


Web*_*her 5

看看这个类似问题的答案

Lodash问题

洛达斯·吉斯特

码:

function toggle(collection, item) {
  var idx = collection.indexOf(item);
  if(idx !== -1) {
    collection.splice(idx, 1);
  } else {
    collection.push(item);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这只是 Xotic750 的答案的副本,其中包含重命名的变量。 (5认同)