我正在嘗試使用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
但結果我得到了錯誤
uj5u.com熱心網友回復:
.includes接受一個必需引數和一個可選引數。第一個是您要匹配的元素。第二個是您要從中開始搜索的索引。
因此,如果要匹配陣列中的物件,請執行以下操作:
this.percentageArray.includes({percValue: this.percValue, lastPerc: this.lastPercentage})
但是,這行不通,因為 JS 將通過參考比較值(標量和字串除外),而不是通過比較物件內部的值。
你應該使用.some():
this.percentageArray.some(element => element.percValue === this.percValue && element.lastPerc === this.lastPercentage)
uj5u.com熱心網友回復:
考慮some改用
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
[
{ 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 },
].some(({percValue, lastPerc }) => percValue === 85 && lastPerc === 60) // true
或者filter,如果您需要訪問該值:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
uj5u.com熱心網友回復:
.includes()在處理原始型別時很有用。在這種情況下,您正在處理被視為非原始型別或復雜型別的物件。
有幾種方法可以處理物件串列,Javascript 提供了一些方法,例如find()或findIndex()。.find()例如,您可以使用:
this.percentValuefromFlag = this.percentageArray.find((elem) => {
return elem.percValue === this.percentValue && elem.lastPerc === this.lastPercentage
})
if (this.percentValuefromFlag) {
console.log(this.percentValuefromFlag)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/338316.html
標籤:javascript
上一篇:如何使用Python高效迭代SeleniumWebdriver中的表號?
下一篇:如何使用反應鉤子形式驗證陣列?
