我正在尝试从特定数组中提取数组项目编号。
例如,如果输入值有一个介于 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))