javascript - 从数组中删除未经检查的值
问题描述
当值 (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
解决方案
你必须寻找indexOf
value
inspecArr
而不是valueOf
specArr
inspecArr
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
推荐阅读
- python - How do I write a Python class that is a node in a linked list while using type hinting
- python - RASA - rasa 运行操作 - 本地主机问题
- swift - How to run Swift binaries compiled on macOS on Linux?
- flutter - PlatformException(already_active, Image picker is already active, null) on huawei y5
- delphi - Delphi XE6 crashes while installing bpl
- sql - 查询时有持续时间的多种情况(Redshift)
- jquery - 使用 jQuery 中的本地存储将数据打印到表中
- angular - 是否可以在带有参数的组件中提供服务?
- java - 如何同时使用前置和后置摄像头?
- ios - 如何处理离子无限重新加载ios应用程序