实际上,我已经使用 Vlookup 在 Excel 上制作了此内容,但现在我在网页上制作了此内容。
我有一个输入框,用户将在其中输入值
<input class="text" type="text" name="rawScore" onchange="calcpercentile()">
我有一个用户可以获得结果的范围
<span id="percentile"></span>
我有两个数组
var percentile = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var rawScores = [1, 3, 5, 7, 10, 12, 18, 25, 27];
如果我写的话我应该写什么代码才能得到
input value
(rawScores) (percentile)
1 10
2 20
3 30
4 40
最佳答案
你的例子似乎是错误的。我希望分数 1 映射到第 10 个百分位数,2 和 3 映射到第 20 个百分位数,4 映射到第 30 个百分位数。
本质上,我认为您想要做的是:找到大于输入的第一个原始分数的数组索引,并从百分位数数组中返回相应的值。
Javascript 可能看起来像这样:
var percentiles = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var rawScores = [1, 3, 5, 7, 10, 12, 18, 25, 27];
function map(input) {
let index = rawScores.findIndex(rawScore => rawScore >= input);
return percentiles[index];
}
console.log(map(1));
console.log(map(2));
console.log(map(3));
console.log(map(4));
请注意,浏览器支持 Array#findIndex()
是有限的。如果您需要广泛的浏览器支持,基于循环的简单方法可能会更好:
var percentiles = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var rawScores = [1, 3, 5, 7, 10, 12, 18, 25, 27];
function map(input) {
for (var i = 0; i < rawScores.length; i++) {
if (rawScores[i] >= input) {
return percentiles[i];
}
}
}
console.log(map(1));
console.log(map(2));
console.log(map(3));
console.log(map(4));
关于javascript - 类似 JavaScript 中的 Vlookup 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40168317/