最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Math.max() not working as expected - Stack Overflow

programmeradmin1浏览0评论

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 the arguments keyword. – Ted Hopp Commented Dec 19, 2016 at 5:25
Add a ment  | 

2 Answers 2

Reset to default 8

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

发布评论

评论列表(0)

  1. 暂无评论