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);
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);
Share
Improve this question
edited Dec 19, 2016 at 5:16
Alexander O'Mara
60.6k19 gold badges172 silver badges181 bronze badges
asked Dec 19, 2016 at 5:09
krishna tejakrishna teja
1593 silver badges10 bronze badges
3
- 3 Did you have a look at the documentation? – Jeroen Heier Commented Dec 19, 2016 at 5:19
- max doesn't accept an array as input. so Math.max(arraylist) will return NaN – Mahi Commented Dec 19, 2016 at 5:20
-
You're not passing an array; you're passing five separate arguments and giving the name
arr
to the first argument. The other argument values are only accessible through thearguments
keyword. – Ted Hopp Commented Dec 19, 2016 at 5:25
2 Answers
Reset to default 8You 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