2013-02-09 45 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 विधि का उपयोग करें, और push और splice तरीकों को जोड़ना या निकालना आइटम:

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

सरल जावास्क्रिप्ट कार्यक्रम को खोजने के लिए और जोड़ने/सरणी में मान निकालें

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 
}