2012-03-07 14 views
15

Buduję prosty system filtrowania, po prostu chcę dodać ciąg do tablicy i usunąć go, jeśli już tam jest kliknięcie linku. Postaram się wytłumaczyć najlepiej jak potrafię ..Jquery - Simple Array, wciskając element, jeśli go tam już nie ma, usuwając element, jeśli jest tam

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

możesz wypróbować 'indexof' swój ciąg w stosunku do tablicy? jeśli zwróci -1, to 'push', jeśli jest większe niż -1,' pop' – MilkyWayJoe

Odpowiedz

41

$.inArray() zwraca indeks elementu, jeśli zostanie stwierdzone, i -1 inaczej (podobnie jak indexOf(), gdy jest obsługiwany). W związku z tym, można napisać coś takiego:

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

mogę się mylić, ale wierzę, że jest to tak proste, jak przy użyciu podstawowego 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 
}; 

Oczywiście jeśli naprawdę chcesz go uprościć, możesz usunąć niektóre linie i zredukować je do wbudowanego kodowania.

0 > $.inArray(newFilter,filters) ? filters.push(newFilter) : filters.splice($.inArray(newFilter,filters),1); 

absolutnej czystych JS:

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

podziale:

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

'$ .inArray()' jest funkcją jQuery. To nie jest "podstawowy JavaScript" ... – aendrew

+0

@ aendrew Miałem na myśli wuts iinside metody – SpYk3HH

0

Innym sposobem znalazłem:

Usuń:

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

add:

filters.push(newFilter) 
1

Chyba że masz konkretny powód do korzystania z tablic sugerowałbym raczej użycie obiektu.

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

Hej jbabey .. trochę pytanie początkujący jak wyświetlić zawartość w obiekcie za pomocą console.log? obecnie otrzymuję - [obiekt obiekt] – Iamsamstimpson

+1

console.log (myObject.propName) lub console.log (myObject ['propName']) – jbabey

0

Coś takiego?

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

Można użyć funkcji lodash "xor":

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

Jeśli nie masz tablicę jako 2nd parametru można Simpy owinąć zmiennej do tablicy

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

Oto dokument: https://lodash.com/docs/4.16.4#xor

Powiązane problemy