jQuery:检查值是否在数组中,如果是,则删除,如果不是,则添加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14783974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: checking if value is in array, if so, delete, if not, add
提问by hellomello
I'm trying to check if there's a value in the array already. If the value does not exists in array, then it should be added into the array, if the value already exists, it should be deleted.
我正在尝试检查数组中是否已经存在值。如果数组中不存在该值,则应将其添加到数组中,如果该值已存在,则应将其删除。
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
}
});
回答by Guffa
Use the inArray
method to look for a value, and the push
and splice
methods to add or remove items:
使用inArray
方法查找值,使用push
和splice
方法添加或删除项目:
var idx = $.inArray(dataid, selectArr);
if (idx == -1) {
selectArr.push(dataid);
} else {
selectArr.splice(idx, 1);
}
回答by Muthu Kumar
Simple JavaScript program to find and add/remove the value in the array
用于查找和添加/删除数组中的值的简单 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
}
回答by Hardeep Singh
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");
}
}
}