我有一个简单的JavaScript数组对象包含几个数字。
[267, 306, 108]
有没有一个函数能找到这个数组中最大的数?
我有一个简单的JavaScript数组对象包含几个数字。
[267, 306, 108]
有没有一个函数能找到这个数组中最大的数?
当前回答
辞职拯救:
Array.max = function( array ){
return Math.max.apply( Math, array );
};
警告:由于在某些虚拟机上参数的最大数量低至65535,如果您不确定数组有那么小,请使用for循环。
其他回答
你也可以使用forEach:
var maximum = Number.MIN_SAFE_INTEGER; Var数组= [-3,-2,217,9,- 8,46]; array.forEach(功能(价值){ If(值> maximum) { 最大值=值; } }); console.log(最大);/ / 217
使用Array.reduce:
[0,1,2,3,4].reduce(function(previousValue, currentValue){
return Math.max(previousValue,currentValue);
});
您还可以扩展Array以拥有此函数,并使其成为每个数组的一部分。
Array.prototype.max = function(){return Math.max.apply( Math, this )};
myArray = [1,2,3];
console.log( myArray.max() );
要找到数组中最大的数字,您只需要使用Math.max(…arrayName);。它是这样工作的:
let myArr = [1, 2, 3, 4, 5, 6];
console.log(Math.max(...myArr));
要了解更多关于Math.max的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
我刚开始使用JavaScript,但我认为这个方法会很好:
var array = [34, 23, 57, 983, 198];
var score = 0;
for(var i = 0; i = array.length; i++) {
if(array[ i ] > score) {
score = array[i];
}
}