简体   繁体   English

如何用JS找到最高和最低的数字?

[英]How to find the highest and lowest number with JS?

I would like to know why my code isn't working.我想知道为什么我的代码不起作用。 There are different ways to solve this issue using Math.max() and Math.min() , however I do not want any other method for this stage as I'm still learning iterations.使用Math.max()Math.min()有不同的方法可以解决这个问题,但是我不希望在这个阶段使用任何其他方法,因为我仍在学习迭代。

Could anyone tell me why this isn't working as I intended?谁能告诉我为什么这不能按我的预期工作? I want to get the highest number and the lowest number from a string, when I run it:当我运行它时,我想从字符串中获取最高数字和最低数字:

highAndLow("4 5 29 54 4 0 -1 -3209093 -214 -542 -64 -1 -3 -6"); // The result of this is 54 and -3209093 

highAndLow("1 1"); // The result of this is 1 and 0

So as you can see the result for the second try should be 1 and 1 but it gives me 1 and 0.所以你可以看到第二次尝试的结果应该是 1 和 1,但它给了我 1 和 0。

What did I do wrong here?我在这里做错了什么?

function highAndLow(numbers){
    var num;
    var maxNum = 0;
    var minNum =0;
    num = numbers.split(" ").map(Number);

    num.map( function(el){
        if(el >= maxNum) {
            maxNum = el;
        }
        if(el <= minNum) {
            minNum = el;
        }
    });
    console.log(maxNum + ' ' + minNum);
}
highAndLow("4 5 29 54 4 0 -1 -3209093 -214 -542 -64 -1 -3  -6"); **// The result of this is 54 and -3209093**
highAndLow("1 1"); **// The result of this is 1 and 0**

 let arr = [0, 100, 2, 45, 23, 1.5, 45.5]; let min = Math.min(...arr) let max = Math.max(...arr) console.log(min) console.log(max)

Hi, you could use the Math object to obtain min and max values spreading the array as shown above.嗨,您可以使用 Math 对象来获取散布数组的最小值和最大值,如上所示。

It's because you initialize minNum to zero, zero is less than one.这是因为您将minNum初始化为零,零小于一。 That's why the result is 1 and 0.这就是结果是 1 和 0 的原因。

Try something like this:尝试这样的事情:

 let arr = [0, 2, 45, 23]; let min = arr.reduce((prev, curr) => Math.min(prev, curr), Number.MAX_VALUE); let max = arr.reduce((prev, curr) => Math.max(prev, curr), Number.MIN_VALUE); console.log(min, max);

It goes through every value, and looks if it's higher than the current highest (or lower than the current lowest).它遍历每个值,并查看它是否高于当前最高值(或低于当前最低值)。 For more information on reduce() , look here .有关reduce()更多信息,请查看此处

Also look at the answer by @Mario Perez for a slightly more elegant solution另请查看@Mario Perez 的答案,以获得更优雅的解决方案

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

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