You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

复选框勾选/取消时数组元素增删异常的问题排查

Fixing Checkbox Array Add/Remove Logic

Hey there! Let's sort out why your checkbox array behavior isn't working as expected. I've spotted a few key issues in your code that are causing the odd functionality:

What's Wrong with the Original Code?

  • Incorrect element removal: Using tableau.shift() always deletes the first element of the array, not the specific "numero" entry. This means unchecking the box might accidentally remove your initial "0" value instead of "numero", and will break entirely if you add other elements later.
  • No duplicate prevention: If the checkbox gets triggered multiple times (even accidentally), you'll end up with multiple "numero" entries in the array instead of just one.
  • Static console log: Your console.log(tableau) runs only once when the script loads, not when the checkbox state changes—so you won't see the array update in real-time.

Corrected Code

Here's the fixed version with explanations of each change:

var tableau = ["0"];
var checkBox_numero = document.getElementById("numero");

checkBox_numero.addEventListener('change', function () {
  if (this.checked) {
    // Only add "numero" if it's not already present
    if (!tableau.includes("numero")) {
      tableau.push("numero");
    }
  } else {
    // Locate the index of "numero" and remove it if it exists
    const numeroIndex = tableau.indexOf("numero");
    if (numeroIndex !== -1) {
      tableau.splice(numeroIndex, 1);
    }
  }
  // Log the updated array every time the checkbox toggles
  console.log(tableau);
});

Key Improvements

  1. Duplicate check with includes(): Ensures "numero" is only added once, even if the checkbox is toggled on multiple times.
  2. Targeted removal with indexOf() + splice(): Finds the exact position of "numero" in the array. If it exists, splice() removes just that element (instead of arbitrarily deleting the first item).
  3. Real-time logging: Moving console.log inside the event listener lets you see the array's updated state every time the checkbox is checked or unchecked.

内容的提问来源于stack exchange,提问作者DrStrange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:02:40