首页 > 解决方案 > Javascript函数返回数组对象阈值之间的值

问题描述

scores在 JavaScript 中有以下对象:

[
  {
    "id":37,
    "title":"Over achieving",
    "description":"Exceeding expectations",
    "threshold":10,
  },
  {
    "id":36,
    "title":"Achieving",
    "description":"Achieving expectations",
    "threshold":6,
  },
  {
    "id":35,
    "title":"Under achieving",
    "description":"Not achieving expectations",
    "threshold":3,
  }
]

我试图弄清楚如何创建一个方法,该方法将根据分数阈值确定的值返回分数对象。

我尝试了以下方法,但它仅在值等于分数阈值时才返回分数,而不是在它之间。

scores.find(o => o.threshold <= progress && o.threshold >= progress)

所以场景是,一个人的进度value为 5,我想要返回id35 的分数数组项的方法,因为 5 介于 3 和 6 之间。同样,如果进度value是 7,那么我想要方法返回带有id36 的分数数组项,因为 7 介于 6 和 10 之间。

我确定我离我不远了。

标签: javascriptecmascript-6

解决方案


您似乎正在寻找数组中阈值低于或等于 progress的第一项。表达方式

scores.find(o => o.threshold <= progress)

会这样做。


推荐阅读