Har*_*rry 1 javascript arrays sorting percentage
所以我想根据数组中的百分比来选择数组索引。
“数组中的百分比”只是索引的函数,因此对于 11 个元素的数组,50% 的索引将为 5。
const numbers = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
Run Code Online (Sandbox Code Playgroud)
我想我想首先获取数组的长度以获得一个可靠的数字来计算百分比。
numbers.length; // 14
Run Code Online (Sandbox Code Playgroud)
那么我将如何使用百分比进入数组,使用长度来选择最接近的与百分比匹配的索引?例如,如果我想选择最接近数组 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])Run Code Online (Sandbox Code Playgroud)