码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-08-08 10:31:56      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:key   comment   join   java   number   pac   max   数组   console   

前段时间在项目中用到对数组进行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 );   

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

标签:key   comment   join   java   number   pac   max   数组   console   

原文地址:https://www.cnblogs.com/kyshu/p/9440980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!