javascript - 如果阈值是 Number.MIN_VALUE,则查找数组中超过特定​​阈值的最小数的函数不会找到小于 1 的数字。如何解决这个问题?

标签 javascript arrays

我正在编写一个函数,用于将数组排序为数组中的各个数组,但我遇到了 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/

相关文章:

javascript - 使用 Selinium、Scrapy、Python 检索用户个人资料的公共(public) facebook 墙贴

javascript - 在文本字段的任意位置按键?

javascript - 用于打印的 Drupal 弹出窗口

Python ctype 帮助 : working with C unsigned char pointers

在 C 中创建具有三个属性的结构数组的概念

使用字符串数组的 IN 语句的 C# Dapper 问题

javascript - 在 Google Cloud Function 内调用 Promise 函数

javascript - 自定义投影的不稳定叠加行为,Google Maps API v3

c - 在字符串中定位一个元素并在 C 中比较它

java - 如何在 Java 中将对象数组作为参数传递