我正在尝试使用这段代码从未选中的数组中删除一个项目。
function filterSearch() {
var cats = [];
$('.filter-by-type input[type="checkbox"]').change(function() {
var cat = $(this).attr('name') + ', ';
if(this.checked) {
cats += cat;
} else {
cats.splice(cats.indexOf(cat), 1);
}
console.log(cats);
});
}
filterSearch();
我收到错误 Uncaught TypeError: cats.splice is not a function
基本上,如果项目被选中,我想将值添加到 cats[]
数组,如果未选中,则将其删除。任何帮助,将不胜感激。
最佳答案
cats
是一个数组。这里:
if(this.checked) {
cats += cat;
^^
} else {
cats.splice(cats.indexOf(cat), 1);
}
您正在尝试使用 +=
运算符连接一个数组,cats
现在是一个字符串,您应该使用 push方法代替。
if(this.checked) {
cats.push(cat);
} else {
cats.splice(cats.indexOf(cat), 1);
}
关于javascript - array.splice 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31195240/