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

Posted

技术标签:

【中文标题】Jquery - 简单数组,如果项目不存在则推入,如果项目存在则移除项目【英文标题】:Jquery - Simple Array, pushing item in if its not there already, removing item if it is there 【发布时间】:2012-03-25 03:39:52 【问题描述】:

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

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

【问题讨论】:

你可以尝试indexof你的字符串对数组吗?如果它返回-1 你push,如果它大于-1 你pop 【参考方案1】:

我可能是错的,但我相信这就像使用基本的 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);

对于 ABSOLUTE 纯 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 我指的是方法内部的 wuts【参考方案2】:

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

【讨论】:

【参考方案3】:

我发现的另一种方法:

删除:

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

添加:

filters.push(newFilter)

【讨论】:

【参考方案4】:

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

$(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] console.log(myObject.propName) 或 console.log(myObject['propName'])【参考方案5】:

类似的东西?

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

【讨论】:

【参考方案6】:

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

【讨论】:

以上是关于Jquery - 简单数组,如果项目不存在则推入,如果项目存在则移除项目的主要内容,如果未能解决你的问题,请参考以下文章

Javascript ES6,如果存在则从数组中删除项目的最佳方法,如果不存在则添加

将对象推入数组

将对象推入数组并使其不可变

jQuery检查Cookie是不是存在,如果不存在则创建它

在Javascript(jQuery)中将数组推入数组

推入 mongodb 中的文档数组