Jquery - 简单数组,如果元素不存在则添加,如果存在则删除

22

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

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

3
你能尝试将字符串与数组进行indexof操作吗?如果返回-1,就执行push,如果大于-1,就执行pop - MilkyWayJoe
6个回答

54

$.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);
}

9
我可能错了,但我认为这很简单,只需要使用基本的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
};

当然,如果您真的想简化它,可以删除一些行并将其简化为内联编码。
0 > $.inArray(newFilter,filters) ? filters.push(newFilter) : filters.splice($.inArray(newFilter,filters),1);

对于绝对纯粹的JS:

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

分解:

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

@aendrew 我指的是方法内部的内容。 - SpYk3HH

5
您可以使用lodash函数“xor”:
_.xor([2, 1], [2, 3]);
// => [1, 3]

如果您的第二个参数不是数组,您可以将变量简单地包装成一个数组

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

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

xor方法的作用是:创建一个具有唯一数组的数组,每个数组的值不包含在其他给定的数组中。


1

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

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

嘿jbabey..有一个新手问题,我如何使用console.log查看对象中的内容?目前我得到的是-[object Object]。 - Iamsamstimpson
1
console.log(myObject.propName) 或 console.log(myObject['propName']) - jbabey

0

我发现另一种方法:

移除:

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

添加:

filters.push(newFilter)

0

类似这样的东西吗?

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接