javascript或nodejs是否具有访问数组项的索引范围?

时间:2018-08-17 11:20:12

标签: javascript node.js

我在ruby中看到了这段代码

module Plutus
  TAX_RATES = {
    (0..18_200)                => { base_tax_amount:      0, tax_rate: 0 },
    (18_201..37_000)           => { base_tax_amount:      0, tax_rate: 0.19 },
    (37_001..80_000)           => { base_tax_amount:  3_572, tax_rate: 0.325 },
    (80_001..180_000)          => { base_tax_amount: 17_547, tax_rate: 0.37 },
    (180_001..Float::INFINITY) => { base_tax_amount: 54_547, tax_rate: 0.45 }
  }.freeze
end

当值落在范围内时,似乎可以访问数组项。

例如given 18000,就能获得{base_tax_amount: 0, tax_rate: 0}

在javascript或nodejs中是否有任何等效项?

2 个答案:

答案 0 :(得分:3)

不,没有该界面。
您必须重新计算索引或使用Proxy

const TaxRates = new Proxy({}, {
  get(target, prop) {
    switch (true) {
      case prop < 18200:  return { base_tax_amount: 0,     tax_rate: 0 };
      case prop < 37000:  return { base_tax_amount: 0,     tax_rate: 0.19 };
      case prop < 80000:  return { base_tax_amount: 3572,  tax_rate: 0.325 };
      case prop < 180000: return { base_tax_amount: 17547, tax_rate: 0.37 };
      default:            return { base_tax_amount: 54547, tax_rate: 0.45 };
    }    
  }
});

console.log([
  TaxRates[18000],
  TaxRates[35000],
  TaxRates[55000],
  TaxRates[550000],
]);

答案 1 :(得分:0)

您可以将数组作为上限,并将对象作为第二个元素。然后,您需要为该对象找到功能。

var TAX_RATES = [
        [18200, { base_tax_amount: 0, tax_rate: 0 }],
        [37000, { base_tax_amount: 0, tax_rate: 0.19 }],
        [80000, { base_tax_amount: 3572, tax_rate: 0.325 }],
        [180000, { base_tax_amount: 17547, tax_rate: 0.37 }],
        [Infinity, { base_tax_amount: 54547, tax_rate: 0.45 }]
    ],
    getTexRate = value => TAX_RATES.find(([v]) => value <= v)[1];

console.log(getTexRate(0));
console.log(getTexRate(10000));
console.log(getTexRate(20000));
console.log(getTexRate(100000));
console.log(getTexRate(1000000));
.as-console-wrapper { max-height: 100% !important; top: 0; }