javascript 在没有 Math.min 的情况下在 Array 中查找最小值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19432769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:34:36  来源:igfitidea点击:

Find smallest value in Array without Math.min

javascriptarrays

提问by STEEL

How can I find the lowest number in an array without using Math.min.apply?

如何在不使用的情况下找到数组中的最小数字Math.min.apply

var arr = [5,1,9,5,7];

回答by MrCode

If you must use a forloop:

如果必须使用for循环:

var arr = [5,1,9,5,7];
var smallest = arr[0];

for(var i=1; i<arr.length; i++){
    if(arr[i] < smallest){
        smallest = arr[i];   
    }
}

console.log(smallest);

回答by STEEL

Now when look at my own question.. it looks so silly of me.

现在看看我自己的问题..我看起来很傻。

Below would be perfect solution to find the smallest number in an array:

下面将是找到数组中最小数字的完美解决方案:

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts

var arr = [5, 1, 9, 5, 7];

var smallest = arr.sort((a, b) => a - b);

alert(smallest[0]);

回答by tenub

just sort the array and take the first value, easy.

只需对数组进行排序并取第一个值,很简单。

if you must use a for loop:

如果必须使用 for 循环:

var arr = [5,1,9,5,7];
for (var i=0; i<1; i++) {
    arr.sort();
}
return arr[0];

回答by GKBRK

Here's a simple solution using a for loop.

这是一个使用 for 循环的简单解决方案。

var arr = [5,1,9,5,7];
var smallest = arr[0];
for (var i=0; i<arr.length; i++){
    if (arr[i]<smallest){
        smallest = arr[i];
    }
}
return smallest;

Returns 1.

返回 1。

回答by saran

Alternate solution without using for loop (ES6). JavaScript reduce method is a good choice.

不使用 for 循环(ES6)的替代解决方案。JavaScript reduce 方法是一个不错的选择。

var arr = [5,1,9,5,7];
var smallest = arr.reduce((prev,next) => prev>next ? next : prev);
var largest = arr.reduce((prev,next) => prev<next ? next : prev);