我有一个功能,我只调用一次,但是当我在浏览器中运行它时,它似乎运行了两次。
function max() {
console.log( arguments[0] );
return this.max.apply( Math, Array.from( arguments[0] ) );
}
console.log( max( [1,32,42,1] ) );
/*
This is output of console:
------------------------
[1, 32, 42, 1]
1
-Infinity
*/

我想得到一个数组的最大值,我已经知道如何得到它。我只是想知道为什么这个函数看起来像执行两次以及为什么这个函数无法得到正确的结果。
答案 0 :(得分:2)
使用Math.max.apply
function max() {
//console.log( arguments[0] );
return Math.max.apply( Math, arguments[0]);
}
答案 1 :(得分:1)
其中this
引用窗口对象,因此int只是递归地调用相同的函数,因为window.max
引用相同的函数。在第二次调用时,this
引用Math
,因为您在Fuction#apply
中将Math
定义为此参数。在递归调用max函数时,第一个参数为1
,Array.from
创建一个空数组,因此Math.max
返回-Infinity
。
要使其工作,请将this
替换为Math
个对象,但根本不需要Array.from
。
function max() {
return Math.max.apply( Math,arguments[0]);
}
或者简单地将数组作为普通参数传递。
function max(arr) {
return Math.max.apply(Math, arr);
}
答案 2 :(得分:1)
function max() {
console.log( arguments[0] );
return this.max.apply( Math, Array.from( arguments[0] ) );
}
在这个方法中,this
引用了@JaydipJ提到的窗口。如果要传递Math对象;
function max(){
var x=this.max.apply(null,[0,1,2,3]);
console.log(x);
}
max.apply(Math);