如何创建包含键值范围的对象

加里30voos

我正在尝试创建一个对象,该对象应该包含我将用作查找表的键的一系列值。例如,它需要“捕获”范围内的值:500-524、600-650 等。

例如:

const numbers = {
  500 to 524: "20",
  600 to 650: "25"
}

我想通过以下方式访问该值:

user.list.map(list => numbers[user.points]).

我知道我可以将范围内的所有值都作为键,但这会非常低效:

const numbers = {
  "500": "20",
  "501": "20",
  "502": "20",
  "503": "20",
  (...)
}

那么,是否有可能以某种方式包含范围?

克里斯托夫·沃西卡

你可以这样设置:

numbers = [
  {"start": 500, "end": 524, "value": "20"},
  ...
  ...
]

function getFromNumbers(num) {
  for(let i=0; i<numbers.length; i++) {
    numVal = numbers[i];
    if(numVal.start <= num && numVal.end >= num)
      return numVal.value;
  }
}

console.log(user.list.map(list => getFromNumbers(user.points)))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章