关于Math.max对array.join()处理返回NaN

前段时间在项目中用到对数组进行join,在Math.max处理返回数据NaN:
var arr = [1,2,3,45,66] var num = Math.max.apply( null, arr ); console.log( num );

apply的第二个参数是参数数组

如果按照你那样写,用arr.join(','),得到的是字符串,就相当于

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

里面是字符串,肯定是不对的

如果坚持要用字符串拼接参数,可以用eval

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

es6写法:

var arr = [1,2,3,45,66]

var num = Math.max( ...arr );
console.log( num );   
原文地址:https://www.cnblogs.com/kyshu/p/9440980.html