You need to enable JavaScript to run this app. JavaScript遍历公交预留座位数组时indexOf查值始终返回-1的问题
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript遍历公交预留座位数组时indexOf查值始终返回-1的问题

问题根因

Array.prototype.indexOf() 采用*严格相等(===)*规则做元素匹配,不会对不同类型的值做隐式转换。
两组测试的执行差异:

  • 手动执行alert(response.reservedseats.indexOf("1"))时,传入的参数是字符串类型的"1",和数组内存储的字符串格式座位号类型、值完全匹配,可正常返回对应索引
  • 1到12的循环遍历中,变量i是数字类型,拿数字值和数组中的字符串值做严格匹配时,1 === "1"结果恒为false,因此indexOf始终返回-1,逻辑固定走入else分支弹出"not found"
修复方案

循环判断时将数字类型的遍历变量转为字符串,再传入indexOf匹配即可:

for (let i = 1; i <= 12; i++) {
  const targetIndex = response.reservedseats.indexOf(String(i));
  if (targetIndex !== -1) {
    alert("done");
    break; // 可选:匹配成功后终止遍历,避免重复弹出无关提示
  } else {
    alert("not found");
  }
}

兼容混合类型的可选写法

如果后续数组中可能同时存储数字、字符串格式的座位号,可改用统一转字符串的比较逻辑,避免类型不匹配导致的漏判:

for (let i = 1; i <= 12; i++) {
  const isSeatReserved = response.reservedseats.some(seat => String(seat) === String(i));
  if (isSeatReserved) {
    alert("done");
  } else {
    alert("not found");
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.24 01:45:03