javascript - 如何使用数组包含方法。我的方式行不通
问题描述
我正在尝试使用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
但结果我错了
解决方案
.includes
接受一个必需参数和一个可选参数。第一个是您要匹配的元素。第二个是您要开始搜索的索引。
因此,如果要匹配数组中的对象,请执行以下操作:
this.percentageArray.includes({percValue: this.percValue, lastPerc: this.lastPercentage})
但是,这不起作用,因为 JS 将通过引用比较值(标量和字符串除外),而不是通过比较对象内部的值。
您应该.some()
改用:
this.percentageArray.some(element => element.percValue === this.percValue && element.lastPerc === this.lastPercentage)
推荐阅读
- c# - Aysnc 方法仍然阻塞 ui 界面
- python - 由于新安装的 conda 无法找到库,docker build 间歇性失败
- javascript - JS用动画改变源图像
- python - 如果在 python 上打开具有特定 url 的窗口,则执行操作
- java - AuthenticationFaliedException:登录失败 IMAP java
- c# - 如何使用 ASP .NET CORE 从控制器传递 AJAX 响应(真/假)
- azure - 将图像上传到 blob 容器的字节数为零
- r - match.names(clabs, names(xi)) 中的错误:名称与以前的名称不匹配
- ssl - 奇怪的 SSL 公用名不匹配
- php - 在外部脚本中使用 wordpress 操作