2013-02-09 14 views
10
'u ekleyin

Zaten dizimde bir değer olup olmadığını kontrol etmeye çalışıyorum. Değer dizide mevcut değilse, diziye eklenmelidir, eğer değer zaten mevcutsa silinmelidir.jQuery: Değerin dizinin olup olmadığını kontrol etme, eğer öyleyse, sil, değilse,

var selectArr = []; 
$('.media-search').mouseenter(function(){ 
    var $this = $(this); 
    $this.toggleClass('highlight'); 
}).mouseleave(function(){ 
    var $this = $(this); 
    $this.toggleClass('highlight'); 

}).on('click',function(){ 
    var dataid = $(this).data('id'); 

    if(selectArry){ // need to somehow check if value (dataid) exists. 
    selectArr.push(dataid); // adds the data into the array 
    }else{ 
    // somehow remove the dataid value if exists in array already 
    } 


}); 

cevap

25

bir değere aramaya inArray yöntemi kullanın ve push ve splice yöntemleri eklemek veya kaldırmak öğeleri için:

var idx = $.inArray(dataid, selectArr); 
if (idx == -1) { 
    selectArr.push(dataid); 
} else { 
    selectArr.splice(idx, 1); 
} 
0

Basit JavaScript programı bulmak ve eklemek/dizide değerini kaldırmak

var myArray = ["cat","dog","mouse","rat","mouse","lion"] 
var count = 0; // To keep a count of how many times the value is removed 
for(var i=0; i<myArray.length;i++) { 
    //Here we are going to remove 'mouse' 
    if(myArray[i] == "mouse") { 
     myArray .splice(i,1); 
     count = count + 1; 
    } 
} 
//Count will be zero if no value is removed in the array 
if(count == 0) { 
    myArray .push("mouse"); //Add the value at last - use 'unshife' to add at beginning 
} 

//Output 
for(var i=0; i<myArray.length;i++) { 
    console.log(myArray [i]); //Press F12 and click console in chrome to see output 
} 
İlgili konular