使用Array.includes()检查对象数组指定值不生效返回false如何解决?
错误原因
- 你对
includes()方法的使用逻辑完全错误:Array.prototype.includes()的第二个参数是查找起始下标,你传入this.lastPercentage的值60,会被识别为从数组索引为60的位置开始查找,而你的数组总共只有9个元素,从不存在的下标位置查找必然返回false。includes()执行的是严格相等(===)比较,你的数组存储的是结构为{percValue: 数值, lastPerc: 数值}的对象,你直接传入数字85和对象比对,两者类型和值都不匹配,自然返回false。
解决方案
要判断数组中是否存在同时满足percValue等于目标值、lastPerc等于目标值的元素,使用Array.prototype.some()方法即可:
console.log("this.percentValue and this.lastPercentage from flag loop", this.percentValue, this.lastPercentage) // 遍历数组匹配两个字段的条件 this.percentValuefromFlag = this.percentageArray.some(item => { return item.percValue === this.percentValue && item.lastPerc === this.lastPercentage }) console.log("percentvalue and lastPercentage present or not", this.percentValuefromFlag)
该方法会遍历数组的每一项,只要有任意一项符合回调函数中定义的匹配规则就会返回true,全部不符合才会返回false,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者Swapnali Botre
相关产品推荐
相关产品推荐

