首页 > 解决方案 > 如何使用数组包含方法。我的方式行不通

问题描述

我正在尝试使用include()方法在数组中查找现值,但它显示错误的结果。

我有以下相同的代码。

我有以下值的“percentageValue”数组

console.log("this.percentageArray before checking percentValue", this.percentageArray); //below  is answer for the same

// logs
[
  { percValue:  8, lastPerc:  0 },
  { percValue: 27, lastPerc:  0 },
  { percValue: 29, lastPerc: 27 },
  { percValue: 30, lastPerc: 27 },
  { percValue: 35, lastPerc: 27 },
  { percValue: 44, lastPerc: 27 },
  { percValue: 60, lastPerc: 27 },
  { percValue: 35, lastPerc: 27 },
  { percValue: 85, lastPerc: 60 },
}

我编写了检查百分比值 85 的代码

console.log("this.percentValue and this.lastPercentage from flag loop", this.percentValue, this.lastPercentage)// getting this answer(this.percentValue and this.lastPercentage from flag loop 85 60)

this.percentValuefromFlag = this.percentageArray.includes(this.percentValue, this.lastPercentage);

console.log("percentvalue and lastPercentage present or not", this.percentValuefromFlag)//for checking result value

但结果我错了

标签: javascript

解决方案


.includes接受一个必需参数和一个可选参数。第一个是您要匹配的元素。第二个是您要开始搜索的索引。

因此,如果要匹配数组中的对象,请执行以下操作:

this.percentageArray.includes({percValue: this.percValue, lastPerc: this.lastPercentage})

但是,这不起作用,因为 JS 将通过引用比较值(标量和字符串除外),而不是通过比较对象内部的值。

您应该.some()改用:

this.percentageArray.some(element => element.percValue === this.percValue && element.lastPerc === this.lastPercentage)

推荐阅读