按百分比选择数组索引

Choose array index by percentage

所以我想根据它在数组中的百分比选择一个数组索引

“数组中的百分比”只是索引的函数,因此对于 11 元素数组,50% 的索引将是 5。

const numbers = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

我想我想首先通过获取数组的长度来获得一个固定的数字来计算百分比。

numbers.length; // 14

虽然我将如何使用百分比进入数组,使用长度到 select 最接近百分比匹配的索引?例如,如果我想 select 最接近数组 25% 的索引?

我想你正在寻找这样的东西。

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

const percentage = 50

let indexAtPercentage = Math.round((numbers.length - 1) * percentage / 100)

console.log("index: " + indexAtPercentage + "\nnumber at index: " + numbers[indexAtPercentage])

您可以计算给定百分比的索引或值,方法是从数组的长度中减去一个,然后乘以百分比,最后对结果进行取整。

percentage 参数应该是 0.00 (0%) 和 1.00 (100%) 之间的值。

const
  indexOfPercent = (arr, percent) => Math.floor((arr.length - 1) * percent),
  valueOfPercent = (arr, percent) => arr[indexOfPercent(arr, percent)];

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

for (let i = 0; i < numbers.length; i++) {
  const
    percent = i / (numbers.length - 1),
    index = indexOfPercent(numbers, percent),
    value = valueOfPercent(numbers, percent);

  console.log(`${i} ${percent.toFixed(2)} ${index} ${value}`);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

我相信这就像通过从长度中获得所需的百分比标记来计算所需的索引一样清楚。

const numbers = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

let desiredPercentage = 25;

if (desiredPercentage) {

  let indexAtPercent = Math.floor(numbers.length * desiredPercentage / 100);
  
  if (indexAtPercent)
    indexAtPercent--;
    
  console.log(numbers[indexAtPercent]);
}