简体   繁体   English

Javascript - 使用循环和数组查找最大值和最小值,-Infinity/Infinity

[英]Javascript - find max and min values using loop and array, -Infinity/Infinity

Could someone explain to me how does this work.有人可以向我解释这是如何工作的。 In find highest number method every number is larger than -Infinity.在查找最高数方法中,每个数都大于 -Infinity。 Why does it take the highest number?为什么取最高的数字? Same with lowest number finder, how does it selects lowest number, all of the numbers are smaller than Infinity.和最小数查找器一样,它是如何选择最小数的,所有的数都小于无穷大。

//find highest number

var Numbers = [1, 2, 101, 45, 55, 1443];
var l = Numbers.length;
var max = -Infinity;
var i;
for (i = 0; l > i; i++) {

    if (Numbers[i] > max) {

        max = Numbers[i];

    }

}

console.info(max);

//find lowest number

var Numbers = [1, 2, 101, 45, 55, 1443];
var l = Numbers.length;
var max = Infinity;
var i;
for (i = 0; l > i; i++) {

    if (Numbers[i] < max) {

        max = Numbers[i];

    }

}

console.info(max);

The key is here.关键在这里。

if (Numbers[i] > max) {

    max = Numbers[i];

}

If the current number is greater than the current maximum number then we make that the max number.如果当前数量大于当前最大数量,那么我们将其设为最大数量。 And we continue until we go trough the entire array.我们继续,直到我们遍历整个阵列。

Starting with -Infinity ensures that any value in the array will be greater or equal to it.以 -Infinity 开头可确保数组中的任何值都大于或等于它。

For the minimum it's the same but we always keep the smallest value we find in the list.对于最小值,它是相同的,但我们始终保留在列表中找到的最小值。

Infinity and -Infinity are values javascript provides, they are greater or smaller than any other value of type Number . Infinity 和 -Infinity 是 javascript 提供的值,它们大于或小于Number类型的任何其他值。 You can find more about them here .您可以在此处找到有关它们的更多信息。

You could debug your code and see exactly what's happening step by step.您可以调试您的代码并逐步查看正在发生的事情。 Checkthis link on how to do that in Chrome.查看此链接了解如何在 Chrome 中执行此操作。

Using console, you can see that for lowest number if condition only true for once when 1 is less than Infinity .使用控制台,您可以看到if条件仅在1小于Infinity时为真一次,则为最低数字。 Other times it always return false because all other numbers are less then 1 so here the logic is if number from array is lower than max then it store else loop continues to looping.其他时候它总是返回 false,因为所有其他数字都小于1所以这里的逻辑是如果数组中的数字低于最大值,那么它存储 else 循环继续循环。

Same for highest number.最高数字相同。

 //find highest number var Numbers = [1, 2, 101, 45, 55, 1443]; var l = Numbers.length; var max = -Infinity; var i; for (i = 0; l > i; i++) { if (Numbers[i] > max) { console.log(i + ' max number' + Numbers[i]); max = Numbers[i]; } } console.info(max); //find lowest number var Numbers = [1, 2, 101, 45, 55, 1443]; var l = Numbers.length; var max = Infinity; var i; for (i = 0; l > i; i++) { if (Numbers[i] < max) { console.log(i + ' lowest number' + Numbers[i]); max = Numbers[i]; } } console.info(max);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM