我正在尝试检查数组中是否有值。如果数组中不存在该值,则应将其添加到数组中,如果该值已存在,则应将其删除。
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
}
});
答案 0 :(得分:28)
使用inArray
方法查找值,使用push
和splice
方法添加或删除项目:
var idx = $.inArray(dataid, selectArr);
if (idx == -1) {
selectArr.push(dataid);
} else {
selectArr.splice(idx, 1);
}
答案 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
}
答案 2 :(得分: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");
}
}