我有一个简单的JavaScript数组对象包含几个数字。
[267, 306, 108]
有没有一个函数能找到这个数组中最大的数?
我有一个简单的JavaScript数组对象包含几个数字。
[267, 306, 108]
有没有一个函数能找到这个数组中最大的数?
当前回答
简单的一行
[].sort().pop()
其他回答
你可以对数组进行降序排序,得到第一项:
[267, 306, 108].sort(function(a,b){return b-a;})[0]
你可以使用apply函数,调用Math.max:
var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306
它是如何工作的?
apply函数用于调用具有给定上下文和参数的另一个函数,以数组形式提供。min和max函数可以接受任意数量的输入参数:Math。Max (val1, val2,…valN)
如果我们调用:
Math.min.apply(Math, [1, 2, 3, 4]);
apply函数将执行:
Math.min(1, 2, 3, 4);
注意,第一个参数context对于这些函数并不重要,因为它们是静态的。不管传递什么作为上下文,它们都将工作。
我不是JavaScript专家,但我想看看这些方法是如何叠加的,所以这对我来说是一个很好的练习。我不知道这在技术上是否是性能测试的正确方法,但我只是一个接一个地运行它们,正如您在代码中看到的那样。
排序和获取第0个值是目前为止最糟糕的方法(它会修改数组的顺序,这可能是不可取的)。对于其他的,差异是可以忽略不计的,除非你谈论的是数百万个索引。
5次运行100,000个索引的随机数数组的平均结果:
Reduce的运行时间为4.0392 ms Math.max.apply运行了3.3742毫秒 排序和获取第0个值花费了67.4724毫秒 数学。Max within reduce()运行了6.5804 ms 自定义findmax函数运行了1.6102 ms
var performance = window.performance
function findmax(array)
{
var max = 0,
a = array.length,
counter
for (counter=0; counter<a; counter++)
{
if (array[counter] > max)
{
max = array[counter]
}
}
return max
}
function findBiggestNumber(num) {
var counts = []
var i
for (i = 0; i < num; i++) {
counts.push(Math.random())
}
var a, b
a = performance.now()
var biggest = counts.reduce(function(highest, count) {
return highest > count ? highest : count
}, 0)
b = performance.now()
console.log('reduce took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest2 = Math.max.apply(Math, counts)
b = performance.now()
console.log('Math.max.apply took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest3 = counts.sort(function(a,b) {return b-a;})[0]
b = performance.now()
console.log('sorting and getting the 0th value took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest4 = counts.reduce(function(highest, count) {
return Math.max(highest, count)
}, 0)
b = performance.now()
console.log('Math.max within reduce() took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest5 = findmax(counts)
b = performance.now()
console.log('custom findmax function took ' + (b - a) + ' ms to run')
console.log(biggest + '-' + biggest2 + '-' + biggest3 + '-' + biggest4 + '-' + biggest5)
}
findBiggestNumber(1E5)
Var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort (); nums.reverse (); alert (num [0]);
最简单的方法:
var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]);
简单的一行
[].sort().pop()