最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - array.splice is not a function - Stack Overflow

programmeradmin2浏览0评论

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

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.

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

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.

Share Improve this question asked Jul 2, 2015 at 21:50 Juan RangelJuan Rangel 1,7931 gold badge19 silver badges37 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 10

cats is a array. Here:

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

You are trying to concatenate an array with the += operator, cats is now a string, you should use the push method instead.

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

评论列表(0)

  1. 暂无评论