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