To find the maximum and minimum in an array we can use Math.max and Math.min function that returns the largest and smallest of zero or more numbers.
Syntax : - Math.max([value1[, value2[, ...]]])
Using apply,you can choose your own context. Apply lets you write shorter code as it allows you to use built-ins functions for some tasks, else we would have to work by looping over the array values.
Here is the code for its understanding:
var arr = [43,4,65,1,8,9,11,345,234,111];
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
console.log(Max value is: "+arr.max()+"\nMin value is: "+ arr.min());
The above code will give you the output as:
Max value is: 345
Min value is: 1
Apply is a convenient way to pass an array of data as parameter.
0 Comment(s)