Jquery - 简单数组,如果项目不存在则将项目推入,如果项目存在则删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9604389/
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-08-27 11:02:58  来源:igfitidea点击:

Jquery - Simple Array, pushing item in if its not there already, removing item if it is there

jqueryarraysfilter

提问by Iamsamstimpson

I'm building a simple filtering system, I simply want to add a string to an array and remove it if its already there on click of a link. I'll try to explain the best I can..

我正在构建一个简单的过滤系统,我只想将一个字符串添加到一个数组中,并在单击链接时将其删除。我会尽我所能解释..

$(document).ready(function(){
    //so I start with an empty array
    var filters [];
    //when a link is clicked I want to add it to the array..
    $('li a', context).click(function(e){
        //so I get the value held in the data-event attribute of the clicked item example: "john"
        newFilter = $(this).attr('data-event');
        //this is where I get stuck, I want to test to see if the string I now have
        //in 'newFilter' is in the array already or not.. if it is in the array I
        //want to remove it, but if it doesnt exist in the array i want to add it..
        if(jQuery.inArray(newFilter, filters){
            //add to array
        } else {
           //remove from array
        };
    e.preventDefault();
    });
});

回答by Frédéric Hamidi

$.inArray()returns the index of the item if it is found, and -1otherwise (just like indexOf()does, when supported). Therefore, you can write something like:

如果找到,$.inArray()返回项目的索引,-1否则(就像indexOf()一样,如果支持)。因此,您可以编写如下内容:

var found = jQuery.inArray(newFilter, filters);
if (found >= 0) {
    // Element was found, remove it.
    filters.splice(found, 1);
} else {
    // Element was not found, add it.
    filters.push(newFilter);
}

回答by SpYk3HH

I could be wrong, but I believe this is as simple as using basic javascript: [.push, .splice]

我可能是错的,但我相信这就像使用基本的 javascript 一样简单:[.push, .splice]

if($.inArray(newFilter, filters)<0) {
    //add to array
    filters.push(newFilter); // <- basic JS see Array.push
} 
else {
    //remove from array
    filters.splice($.inArray(newFilter, filters),1); // <- basic JS see Array.splice
};

Of course if you really want to simplify it you could remove some lines and reduce it to inline coding.

当然,如果您真的想简化它,您可以删除一些行并将其减少为内联编码。

0 > $.inArray(newFilter,filters) ? filters.push(newFilter) : filters.splice($.inArray(newFilter,filters),1);


For ABSOLUTE pure JS:

对于绝对纯 JS:

var i; (i=filters.indexOf(newFilter))<0?filters.push(newFilter):filters.splice(i,1);

Broken down:

分解:

var i;  //  Basic variable to be used if index of item exist
//  The following is simply an opening to an inline if statement.
//  It's wrapped in () because we want `i` to equal the index of the item, if found, not what's to follow the `?`.
//  So this says "If i = an index value less than 0".
(i=filters.indexOf(newFilter)) < 0 ?
    //  If it was not found, the index will be -1, thus push new item onto array
    filters.push(newFilter) : 
        //  If found, i will be the index of the item found, so we can now use it to simply splice that item from the array.
        filters.splice(i,1);

回答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 jbabey

Unless you have a specific reason for using arrays, I would suggest using an object instead.

除非您有使用数组的特定原因,否则我建议改用对象。

$(document).ready(function(){
    //so I start with an empty array
    var filters {};
    //when a link is clicked I want to add it to the array..
    $('li a', context).click(function(e){
        //so I get the value held in the data-event attribute of the clicked item example: "john"
        newFilter = $(this).attr('data-event');
        //this is where I get stuck, I want to test to see if the string I now have
        //in 'newFilter' is in the array already or not.. if it is in the array I
        //want to remove it, but if it doesnt exist in the array i want to add it..
        if (filters.hasOwnProperty(newFilter)) {
           // remove from object
           delete filters[newFilter];
        } else {
           //add to object
           filters[newFilter] = 'FOO'; // some sentinel since we don't care about value 
        };
    e.preventDefault();
    });
});

回答by GiDo

Something like thats ?

类似的东西?

var filters = [];
// ...
var newFilter = '...';
if(-1 !== (idx = jQuery.inArray(newFilter, filters))) {
   // remove
   filters.splice(idx, 1);
} else {
   // add
   filters.push(newFilter);
}

回答by Ofir Baruch

Another way I've found:

我发现的另一种方法:

Remove:

消除:

filters = jQuery.grep(filters, function(value) {
  return value != newFilter;
});

add:

添加:

filters.push(newFilter)