我需要计算大数组的最小值/最大值。我知道Math.max.apply()
,但是对于大型数组,它会因堆栈溢出异常而失败。任何简单的解决方案?
答案 0 :(得分:5)
由于数组按升序排序,因此最后一个元素是max
var arr = [1,4,6,4 ....
arr.sort();
var max = arr [arr.length-1];
答案 1 :(得分:3)
Array.prototype.min = function() {
var r = this[0];
this.forEach(function(v,i,a){if (v<r) r=v;});
return r;
};
来自JavaScript: min & max Array values?,其中讨论了此问题的其他解决方案
仅供参考:我刚用google搜索“max min large array”,发现这是第一个结果......
答案 2 :(得分:2)
为什么不循环遍历整个阵列?
var max = Number.MIN_VALUE, min = Number.MAX_VALUE;
for (var i = 0, len=list.length; i < len; i++) {
if (list[i] > max) max = list[i];
if (list[i] < min) min = list[i];
}
修改强>
最多:
if (typeof Array.prototype.GetMax === "undefined") {
Array.prototype.GetMax = function() {
var max = Number.MAX_VALUE;
for (var i = 0, len=this.length; i < len; i++) {
if (this[i] > max) max = this[i];
}
return max;
}
}
对于min:
if (typeof Array.prototype.GetMin === "undefined") {
Array.prototype.GetMin = function() {
var min = Number.MIN_VALUE;
for (var i = 0, len=this.length; i < len; i++) {
if (this[i] < min) min = this[i];
}
return min;
}
}
对于两者:
if (typeof Array.prototype.GetMaxMin === "undefined") {
Array.prototype.GetMaxMin = function() {
var max = Number.MIN_VALUE, min = Number.MAX_VALUE;
for (var i = 0, len=this.length; i < len; i++) {
if (this[i] > max) max = this[i];
if (this[i] < min) min = this[i];
}
return { Max: max, Min: min};
}
}
答案 3 :(得分:0)
我应该假设你已经想到了这个:
var maxSoFar = -9999999;
for (var i = 0; i < array.length ; ++i) {
if (array[i] > maxSoFar) {
maxSoFar = array[i];
}
... similar for minSoFar ...
}
答案 4 :(得分:0)
试试这个
var arr = [];
for(var i=1000000;i>0;i--)
{
arr.push(i);
}
//we create a copy of the original array through arr.concat() since we do not want to change the original sorting order of the array
//we pass a function in the sort method as by default it sorts alphabetically instead of numerically. So 99 will be smaller than 100.
var arrMaxMin = arr.concat().sort(function(a,b){return a-b});
arrMaxMin[0]; //min
arrMaxMin[arrMaxMin.length - 1]; //max
答案 5 :(得分:0)
嘿,为什么不将数组切割成较小的数组,然后在数组上可以轻松使用Math.max.apply(数学,单个数组)。但是请记住将所有子数组重新初始化为null,以便重新获得内存一次获得所需的最大值