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

标签 jquery arrays 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();
    });
});

最佳答案

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

关于Jquery - 简单数组,如果项目不存在则将其插入,如果存在则删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604389/

相关文章:

javascript - Jquery next 没有正确迭代

javascript - 页面完全加载事件

java - 如何构建一个数组并将其与另一个数组进行比较?

java - 多维数组操作 - Java

windows - 上层设备过滤驱动INF安装文件

javascript - 一次性弹出框 (SweetAlert2)

jQuery scrollTop 不适用于查询字符串链接

java - 为什么在 Java 中创建一个 MAX_INT 大小的数组是不可能的?

php - 如何在 PHP 中更快地过滤我的电子邮件?

javascript - JS : delete first element from array by value