Jquery - Simple Array, вставка элемента, если его там еще нет, удаление элемента, если он там есть - PullRequest
18 голосов
/ 07 марта 2012

Я строю простую систему фильтрации, я просто хочу добавить строку в массив и удалить ее, если она уже существует при нажатии ссылки. Я постараюсь объяснить, как могу ..

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

Ответы [ 6 ]

48 голосов
/ 07 марта 2012

$. 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);
}
7 голосов
/ 07 марта 2012

Я могу ошибаться, но я считаю, что это так же просто, как использовать базовый 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 pure 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);
4 голосов
/ 20 октября 2016

Вы можете использовать функцию 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

1 голос
/ 07 марта 2012

Если у вас нет особых причин для использования массивов, я бы предложил вместо этого использовать объект.

$(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();
    });
});
0 голосов
/ 07 марта 2012

Что-то в этом роде?

var filters = [];
// ...
var newFilter = '...';
if(-1 !== (idx = jQuery.inArray(newFilter, filters))) {
   // remove
   filters.splice(idx, 1);
} else {
   // add
   filters.push(newFilter);
}
0 голосов
/ 07 марта 2012

Другой способ, который я нашел:

Удалить:

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

Добавить:

filters.push(newFilter)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...