我正在尝试从特定数组中提取数组项编号。
例如,如果输入值的数字介于 2.59 和 2.79 之间,例如 2.65
使用此函数的输出
const gpaToLevel = [].concat(...
[1.99, 2.19, 2.39, 2.59, 2.79, 2.99, 3.19, 3.39, 3.59, 3.79, 4.00].map((ending, j, endValue) =>
Array(ending - (endValue[j-1] || -1)).fill(j)
)
);
应该是 4,因为 2.65 小于 2.79,并且 2.79 的值为 [4]。
谢谢
最佳答案
我认为您正在寻找的是 findIndex()
。它接受回调并返回回调返回 true
的第一个项目的索引。
因此,如果您的数组已排序,您可以使用:
arr = [1.99, 2.19, 2.39, 2.59, 2.79, 2.99, 3.19, 3.39, 3.59, 3.79, 4.00]
// 4
console.log(arr.findIndex(item => item > 2.65))
// 5
console.log(arr.findIndex(item => item > 2.85))
// 0
console.log(arr.findIndex(item => item > 1.85))
// -1 -- no items greater than 4.0
console.log(arr.findIndex(item => item > 4.5))
关于javascript - 尝试从数字列表中提取数组值,但返回的值无效数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53975266/