12

我正在尝试检查数组中是否已经存在值。如果数组中不存在该值,则应将其添加到数组中,如果该值已存在,则应将其删除。

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
    }


}); 
4

3 回答 3

36

使用inArray方法查找值,使用pushandsplice方法添加或删除项目:

var idx = $.inArray(dataid, selectArr);
if (idx == -1) {
  selectArr.push(dataid);
} else {
  selectArr.splice(idx, 1);
}
于 2013-02-09T01:42:38.383 回答
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
}  
于 2018-02-12T07:48:49.207 回答
0
  function AddingOffences() {

var sendingcountry = ary.filter((item) => {
  return (item.Offence.toLowerCase().indexOf($("#ddl_OffencesByLocation option:selected").val()) > -1);
})
if (sendingcountry == "") {

  if ($("#txtPriceByLocation").val() == "") {
    alert("Please select price")
  } else {



    $("#Div_OffenceListByLoction").append("<li id=" + $("#ddl_OffencesByLocation option:selected").val() + ">" + $("#ddl_OffencesByLocation option:selected").text() + "<span>" + $("#txtPriceByLocation").val() + " kr" + "</span><span onclick='RemoveOffence(" + $("#ddl_OffencesByLocation option:selected").val() + ")' > Remove</span></li>");
    pushToAry($("#ddl_OffencesByLocation option:selected").val(), $("#txtPriceByLocation").val());
  }
  } else {
    alert("Allready Exist");
  }

}

于 2019-11-12T07:27:00.450 回答