当前位置:网站首页>Math. Max() method obtains the maximum value in the array and returns Nan problem analysis

Math. Max() method obtains the maximum value in the array and returns Nan problem analysis

2022-06-23 23:39:00 Deshun

Today, someone in the group asked Math.max() Method returns NaN The problem of , Let me give you a simple example , Look at the picture below :

It looks fine , But why return  NaN  Well ? Let's take a brief look at  Math.max()  Method :

Math.max()

Math.max() Function returns the maximum value of a set of numbers .

Demo:

console.log(Math.max(1, 3, 2));
// expected output: 3

console.log(Math.max(-1, -3, -2));
// expected output: -1

const array1 = [1, 3, 2];

console.log(Math.max(...array1));
// expected output: 3

grammar :

Math.max(value1[,value2, ...])

Parameters : A set of values

value1, value2, ...

Return value :

Returns the maximum of a given set of numbers .

Be careful : If at least one of the given parameters cannot be converted to a number , Will return NaN.

Problem solving

Careful observation shows that , The code uses ... deconstruction , No problem ,ES6 The syntax supports this , Will solve the array into a set of values .

But the problem here is array  Is a two-dimensional array , Deconstructed or an array , Not numbers , So back NaN 了 .

besides , There will also be some scenes NaN , A simple example :

var arr=[1,2,3,45,66]
var num =Math.max(arr.join(','))
alert(num)

If you write like this , use arr.join(',') What you get is a string , It is equivalent to a string :

Math.max( '1,2,3,45,66' );

resolvent :

var arr = [1,2,3,45,66]
var num = Math.max.apply( null, arr );
console.log( num );

apply The second parameter to is the parameter array .

perhaps :

var arr = [1,2,3,45,66]
var num = eval( 'Math.max(' + arr.join( ',' ) + ')' );
console.log( num ); // 66

If you insist on splicing parameters with strings , It can be used eval Method .

No reprint without permission :w3h5 » Math.max() Method to get the maximum value in the array and return NaN Problem analysis

原网站

版权声明
本文为[Deshun]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/20211208164239407b.html