首页 > 解决方案 > 从数组中删除未经检查的值

问题描述

当值 (item-1) 被选中时,它会显示在控制台中,但是当它被取消选中时,值 (item-1) 仍保留在数组中。当从数组中取消选中 item-1 时,我正在尝试删除它。

const item = document.querySelector('.item');
const value = 'Insert into array';
let specArr = [];

item.addEventListener('change', function (e) {
  
//   Push value into array
    if (item.checked) {
        specArr.push(`${value}`)
        console.log(specArr);

//    Remove value from array
    } else if (!item.checked) {
        let index = specArr.indexOf(specArr)
        if (index != -1) {
            specArr.splice(index, 1);
            console.log(specArr);
        }
    }
})
<input class="item" type="checkbox" > Item 1

标签: javascripthtmlforms

解决方案


你必须寻找indexOf valueinspecArr而不是valueOf specArrinspecArr

let index = specArr.indexOf(value)

const item = document.querySelector('.item');
const value = 'Insert into array';
let specArr = [];

item.addEventListener('change', function(e) {

  //   Push value into array
  if (item.checked) {
    specArr.push(`${value}`)
    console.log(specArr);

    //    Remove value from array
  } else if (!item.checked) {
    let index = specArr.indexOf(value)
    if (index != -1) {
      specArr.splice(index, 1);
      console.log(specArr);
    }
  }
})
<input class="item" type="checkbox"> Item 1


推荐阅读