2013-02-09 37 views
10

我想检查数组中是否有一个值已经。如果该值不存在于数组中,则应将其添加到数组中,如果该值已存在,则应删除该值。jQuery:检查值是否在数组中,如果是这样,删除,如果没有,添加

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 
    } 


}); 

回答

25

使用inArray方法来寻找一个值,pushsplice方法来添加或删除项目:

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

简单的JavaScript程序来查找和添加/数组中删除值

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 
} 
相关问题