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

JavaScript中Array.includes检测for in迭代变量是否在数组中时失效问题

问题解答

核心原因

问题的核心是for...in遍历数组返回的索引为字符串类型,而includes()、indexOf()的匹配逻辑都是严格相等(===),类型不匹配导致判断失败:

  • 执行for(let i in array1)时,i的取值实际是"0"、"1"、"2"、"3",均为字符串类型,你可以在循环内打印typeof i验证该结论。
  • 你要匹配的array2元素是数字类型的1、2,"1" === 1的结果为false,所以includes(i)全部返回false。
  • 直接调用array2.includes(1)时传入的是数字类型,和数组元素类型一致,所以能正常返回true。

修复方案

方案1:将遍历得到的索引转成数字后再判断

const array1 = [0, 1, 2, 3];
const array2 = [1, 2];
for(let i in array1)
    console.log(array2.includes(Number(i)));

方案2:使用更适合数组遍历的for...of直接取元素值(推荐)

const array1 = [0, 1, 2, 3];
const array2 = [1, 2];
// 直接遍历array1的元素值进行匹配
for(let val of array1)
    console.log(array2.includes(val));

方案3:使用普通for循环获取数字类型索引

const array1 = [0, 1, 2, 3];
const array2 = [1, 2];
for(let i = 0; i < array1.length; i++)
    console.log(array2.includes(i));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:15:06