I have this following function, where Math.max() is not working as expected. It is always alerting the 1st value from the arguments that are passing. Where is the mistake?
function large(arr) {
alert(Math.max(arr))
}
large(1,2,3,4,5);
You are passing multiple arguments, but your function only uses the first one.
In ES5 and before, you can use the apply method of a function and the arguments object:
function large() {
alert(Math.max.apply(Math, arguments))
}
large(1,2,3,4,5);
In ES6 you can use the rest and spread operator:
function large(...arr) {
alert(Math.max(...arr))
}
large(1,2,3,4,5);
You can do like this.
If you want to use the arguments you can avoid the parameter of the function. Then use the apply function to call Math.max
function large() {
var _max = Math.max.apply(Math, arguments);
alert(_max)
};
large(1, 2, 3, 4, 5, 20,9000);
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With