Jquery - 简单数组,如果它已经存在则推送项目,如果它存在则移除项目

Iam*_*son 18 arrays jquery filter

我正在构建一个简单的过滤系统,我只想将一个字符串添加到一个数组中,如果已经点击链接就将其删除.我会尽力解释我能做的最好的事情..

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

Fré*_*idi 50

$ .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);
}
Run Code Online (Sandbox Code Playgroud)


SpY*_*3HH 8

我可能错了,但我相信这就像使用基本的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
};
Run Code Online (Sandbox Code Playgroud)

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

0 > $.inArray(newFilter,filters) ? filters.push(newFilter) : filters.splice($.inArray(newFilter,filters),1);
Run Code Online (Sandbox Code Playgroud)

对于ABSOLUTE纯JS:

var i; (i=filters.indexOf(newFilter))<0?filters.push(newFilter):filters.splice(i,1);
Run Code Online (Sandbox Code Playgroud)

细分:

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


Dav*_*nni 5

您可以使用 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)

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