var ary=[1,2,3,4,5,6,7];
var max= eval('Math.max('+ ary.toString()+')');
console.log(max);
ary.toString()去除了数组的中括号 从而 max = eval('Math.max('1,2,3,4,5,6,7')');
eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。
从而 max=Math.max(1,2,3,4,5,6,7);
Math.max()求最大值
其实就是动态执行Math.max(1,2,3,4,5,6,7),eval动态执行js代码用的
var ary=[1,2,3,4,5,6,7];
var max= Math.max.apply(this,ary);
console.log(max);
1.eval(string);用于执行string中的代码;
2.Math.max();用于获取数组中的最大值,但是不能直接接受数组对象作为参数,此处ary.toString()把数组对象转换成字符串对象,然后传给Math.max();eval执行了Math.max("[1,2,3,4,5,6,7]");获取到最大值;
3.通常去最大值的方法借助apply()方法:Math.max.apply(null,[1,2,3,4,5,6,7]);这种方式
上面的那个写法,简单来说的意思 就是 首先生成
Math.max('+ ary.toString()+') = Math.max(1,2,3,4,5,6,7)
然后 eval('Math.max(1,2,3,4,5,6,7)') 使字符串变成一个可执行代码 重新编译
Math.max(array) 没有这个写法 如果里面直接是对象 就需要 Math.max.apply(this,array)