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

jQuery.inArray查询数组中error_check值未返回正确结果问题

问题原因
  • jQuery.inArray() 会直接将匹配值和数组元素做全等匹配,你的error数组元素是对象类型,你传入的匹配值是字符串'error_check',对象和字符串不可能全等,自然无法匹配到结果。
  • 就算存在匹配项,jQuery.inArray() 匹配成功后返回的是对应元素的索引值,你直接把返回值作为if判断条件,若匹配到的是第一个元素(索引为0),0会被判定为假值,依旧会走到else分支,逻辑本身也存在问题。
解决方法

方案1:使用原生Array.some()实现(推荐,无jQuery依赖)

直接遍历数组判断每个对象的size属性是否符合要求,匹配到符合条件的项就会立即返回true:

if (error.some(item => item.size === 'error_check')) {
  console.log("is in array");
} else {
  console.log("is NOT in array");
}

方案2:调整逻辑后使用jQuery.inArray()

先把所有对象的size属性提取为纯字符串数组,再调用jQuery.inArray(),同时判断返回值是否不等于-1(-1代表未匹配到):

// 提取所有size属性组成新数组
const sizeList = error.map(item => item.size);
if (jQuery.inArray('error_check', sizeList) !== -1) {
  console.log("is in array");
} else {
  console.log("is NOT in array");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:48:04