与应用调用相关的问题

时间:2016-09-09 11:39:46

标签: javascript arrays

我有一个功能,我只调用一次,但是当我在浏览器中运行它时,它似乎运行了两次。



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
*/




我想得到一个数组的最大值,我已经知道如何得到它。我只是想知道为什么这个函数看起来像执行两次以及为什么这个函数无法得到正确的结果。

3 个答案:

答案 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函数时,第一个参数为1Array.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);