Javascript array.splice 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31195240/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:21:53  来源:igfitidea点击:

array.splice is not a function

javascriptjqueryarrays

提问by Juan Rangel

I am trying to remove an item from an array of unchecked with this bit of code.

我正在尝试使用这段代码从未经检查的数组中删除一个项目。

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();

I am getting the error Uncaught TypeError: cats.splice is not a function

我收到错误 Uncaught TypeError: cats.splice is not a function

Basically I want to add the value to the cats[]array if the item is checked and removed if unchecked. Any help would be appreciated.

基本上我想将值添加到cats[]数组,如果项目被选中,如果未选中则删除。任何帮助,将不胜感激。

回答by Walter Chapilliquen - wZVanG

catsis a array. Here:

cats是一个数组。这里:

if(this.checked) {
   cats += cat;
        ^^
} else {
   cats.splice(cats.indexOf(cat), 1);
}

You are trying to concatenate an array with the +=operator, catsis now a string, you should use the pushmethod instead.

您正在尝试将一个数组与+=运算符连接起来,cats现在是一个字符串,您应该改用push方法。

if(this.checked) {
   cats.push(cat);
} else {
   cats.splice(cats.indexOf(cat), 1);
}