0

我正在尝试创建一个使用百分比来获取数字的函数。我们的想法是有这样的东西: 0%: 100px 50%: 200px 75%: 210px

因此,当我以 25% 的百分比运行我的函数时,它会将 0 和 50 混合在一起,高于 50% 时也是如此。

听起来有点复杂,总体思路是只使用 JS 创建一些东西,这将简化从 0 到 100% 的数字

我尝试过使用常规百分比计算,但它实际上不适用于 3 个或更多变量。

4

1 回答 1

0

因此,如果您不介意我冒昧地将您的百分比转换为 JSON 对象:

let input = {
  0: 100,
  50: 200,
  75: 210,
};

如果我们假设百分比总是整数,我们可以这样做:

let output = {};
let previous = null;
// for each whole percent
for(let keyPercent in input)
{
  // cast to number
  let currPercent = parseFloat(keyPercent);
  // get value of percent
  let currValue = input[currPercent];
  if (currValue != null) { // if value is present
    if (previous != null) { // and previous value is not null
      // find the step size (valDiff) / (percentDiff)
      let step = (currValue - previous.value) / (currPercent - previous.percent);
      // count to multiply by step
      let count = 0;
      // this produces the percent value for every step between previous.percent and currPercent
      for (let prevPercent = previous.percent; prevPercent <= currPercent; prevPercent += 1) {
        output[prevPercent] = previous.value + (step * count);
        count += 1;
      }
    }
    // set previous value
    previous = { percent: currPercent, value: currValue };
  }
}
console.log(output);

这会输出以下内容:

0: 100
1: 102
2: 104
...
48: 196
49: 198
50: 200
51: 200.4
52: 200.8
...
73: 209.2
74: 209.6
75: 210

如果您需要任何澄清,请告诉我。

注意:注释是在代码中进行的

于 2019-06-12T16:41:30.887 回答