Let me introduce a Javascript array, it is a variable that stores more than one value, string or integer both. This post is about integers, when you want to find the maximum value in an array.
Lets assume this array:
var numbers = [11, 22, 33, 99, 44, 55, 66, 77, 88]Now we know that 99 is the max value in this one so the return value should be 99. So the first step is to create a variable that holds a value.
March 9, 2015Updated after getting hilarious comments on Google Plus
Method 1 : Easy as pie
This one works with built in method to determine the max value of an array. The method have uses math max function.
Math.max.apply(null.arr)So the final code would be:
function getmax() {
var numbers = [11, 22, 33, 99, 44, 55, 66, 77, 88],
max = Math.max.apply(null,numbers);
console.log(max);
}
getmax();
Method 2 : A complex but works finely
var max=numbers[0];Now, above I create a variable that will have the first value of array (numbers). Now create a loop that will compare the array and max value. If value of array greater than max then the variable will be changed and you can access the maximum value of array from variable max.
function getmax() {
var numbers = [11, 22, 33, 99, 44, 55, 66, 77, 88],
max = numbers[0];
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
console.log(max);
}
}
}
getmax();
Post A Comment:
0 comments: