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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17153238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:17:56  来源:igfitidea点击:

How to toggle an element in array using JavaScript?

javascriptarraysunderscore.jstoggle

提问by wwli

Here is my code for javascript for this simple task:

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

  1. Removethe element if it exists in an array.
  2. Addthe element if it is not in an array.

    if(_.contains(this.types,type_id)){
        var index = this.types.indexOf(type_id);
        this.types.splice(index,1);
    }
    else{
        this.types.push(type_id);
    }
    
  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);
    }
    

Is there a more efficient way to do this?

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

采纳答案by 6502

If you care about efficiency then may be using an array to implement a set is a bad idea. For example using an object you could do:

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

function toggle(S, x) {
    S[x] = 1 - (S[x]|0);
}

then after many add/remove operations you can keep only keys where the value is 1

然后经过多次添加/删除操作后,您只能保留值为 1 的键

This way every addition/removal is O(1)and you need only one O(n)operation to get the final result.

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

If keys are all "small" numbers may be a bitmask is even worth the effort (not tested)

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

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

回答by Xotic750

You could do it without a 3rd party library, this would be more efficient, like this. (this only removes the first instance of a value if found, not multiple)

你可以在没有 3rd 方库的情况下做到这一点,这会更有效率,就像这样。(如果找到,这只会删除值的第一个实例,而不是多个)

Javascript

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);

Output

输出

[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] 

On jsfiddle

jsfiddle 上

回答by David Ginanni

You can use the lodash function "xor":

您可以使用 lodash 函数“xor”:

_.xor([2, 1], [2, 3]);
// => [1, 3]

If you don't have an array as 2nd parameter you can simpy wrap the variable into an array

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

var variableToInsertOrRemove = 2;
_.xor([2, 1], [variableToInsertOrRemove]);
// => [1]
_.xor([1, 3], [variableToInsertOrRemove]);
// => [1, 2, 3]

Here's the doc: https://lodash.com/docs/4.16.4#xor

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

回答by YairTawil

For immutablestate ( clone array ):

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

const addOrRemove = (arr, item) => arr.includes(item) ? arr.filter(i => i !== item) : [ ...arr, item ];

回答by WebBrother

Look at this answerof similar question.

看看这个类似问题的答案

Lodash issue

Lodash 问题

Lodash gist

洛达什要点

Code:

代码:

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

回答by nclu

If "types" can be a Set then

如果“类型”可以是一个集合,那么

let toggle = type_id => this.types.delete(type_id) || this.types.add(type_id);

回答by Flavien Volken

Using underscorejs

使用下划线

function toggle(a,b)
{
return _.indexOf(a,b)==-1?_.union(a,[b]):_.without(a,b);
}

Usage:

用法:

var a = [1,2,3];
var b = [4];
a = toggle(a,b); // [1,2,3,4]
a = toggle(a,b); // [1,2,3]

回答by Abhay Raj Singh Rathod

Extending Xotic750's answerthis will always ensure that toggled elements occur only oncein array. You this if your arrays are bit random like user inputs.

扩展Xotic750 的答案,这将始终确保切换元素在数组中出现一次。如果您的数组像用户输入一样有点随机,那么您就可以这样做。

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());