Javascript jquery从数组中添加/删除项

Javascript jquery从数组中添加/删除项,javascript,jquery,arrays,Javascript,Jquery,Arrays,我有一个复选框3-4,当用户选中复选框时,我想将复选框的值添加到数组中,如果他们取消选中复选框,我想从数组中删除该项,这就是我目前得到的结果: $('ul.dropdown-menu input[type=checkbox]').each(function () { $(this).change(function () { if ($(this).attr("id") == 'price') { if (this.checked) {

我有一个复选框3-4,当用户选中复选框时,我想将复选框的值添加到数组中,如果他们取消选中复选框,我想从数组中删除该项,这就是我目前得到的结果:

$('ul.dropdown-menu input[type=checkbox]').each(function () {
    $(this).change(function () {

        if ($(this).attr("id") == 'price') {
            if (this.checked) {
                priceArray.push($(this).val());
            }
            else {
                priceArray = jQuery.grep(priceArray, function (value) {
                    return value != $(this).val();
                });
            }
        }
    });
});
将值添加到数组中效果很好,但是删除项会导致此错误:

Cannot read property 'toLowerCase' of undefined
在这一行:

return value != $(this).val();
您可以尝试使用,而不是:

var值=[];
$(“输入”)。关于(“更改”,函数()
{
var$this=$(this);
如果($this.is(“:checked”))
{
value.push($this.val());
}
其他的
{
values=values.filter(x=>x!=$this.val());
}
console.log(值);
});

更换

priceArray = jQuery.grep(priceArray, function (value) {
    return value != $(this).val();
});


不要忘记回调函数中的作用域。

您可以使用函数式非常简洁地完成此操作

<div class="checkboxes">    
  <input type="checkbox" value="1" />
  <input type="checkbox" value="2" />
</div>

运行代码段并检查


var priceArray=[];
$(文档).ready(函数(){
$('input[type=checkbox]')。每个(函数(){
$(此).change(函数(){
如果(选中此项){
priceArray.push($(this.val());
$(“#displayarray”).html(“数组=[“+priceArray+”]);
}
否则{
var index=priceArray.indexOf($(this.val());
如果(索引>-1){
priceArray.拼接(索引,1);
}
$(“#displayarray”).html(“数组=[“+priceArray+”]);
}
});
});
});
框1
框2
框3
方框4


提供完整的代码。提供完整的代码html代码在哪里?如果没有导致错误的代码,这意味着左操作数未定义,不能对其应用
toLowerCase
。请提供此代码,否则这充其量只是猜测。为什么不循环检查复选框,每次都得到选中的复选框,而不是使用循环添加/删除。
<div class="checkboxes">    
  <input type="checkbox" value="1" />
  <input type="checkbox" value="2" />
</div>
(function() {
    $(".checkboxes input[type=checkbox]").on("click", function() {
        var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
        return parseFloat(b.value);
      }).toArray();
      console.log(x)
    });
})();