我正在编写一个函数,用于将数组排序为数组中的各个数组,但我遇到了 Number.MIN_VALUE 的一些问题。在第一次运行时,阈值设置得尽可能低,以找到最小值,然后将其设置为下一次运行的阈值。但是,将阈值设置为 Number.MIN_VALUE 时,第一次运行仅返回最小的正数,不包括负数和 0。
如果我将 Number.MIN_VALUE 替换为值,例如 -20,一切正常。但是,如果我不知道数组中的最低数字,可能会有问题。
const findNumberOverThreshold = (arr, threshold) => {
let number = Number.MAX_VALUE;
for (item of arr) {
if (item < number && item > threshold)
number = item;
}
return number;
}
const array = [-10, 0, 1, 5];
const num = findNumberOverThreshold(array, Number.MIN_VALUE);
console.log({
num
})
预期输出
findNumberOverThreshold(array, Number.MIN_VALUE)
会是-10,但实际输出是1。
最佳答案
根据 MDN :
The Number.MIN_VALUE property represents the smallest positive numeric value representable in JavaScript.
您可以使用 Number.NEGATIVE_INFINITY
反而。
const findNumberOverThreshold = (arr, threshold) => {
let number = Number.MAX_VALUE;
for (item of arr) {
if (item < number && item > threshold)
number = item;
}
return number;
}
const array = [-10, 0, 1, 5];
const num = findNumberOverThreshold(array, Number.NEGATIVE_INFINITY);
console.log({
num
})
关于javascript - 如果阈值是 Number.MIN_VALUE,则查找数组中超过特定阈值的最小数的函数不会找到小于 1 的数字。如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54296124/