Discuss / JavaScript / apply( ) 的主要应用就是用来接收数量不定的参数

apply( ) 的主要应用就是用来接收数量不定的参数

Topic source
var a = [3, 5, 4];
alert(Math.max(a)); // NaN
alert(Math.max.apply(null, a)); // 5

Math.max接收的参数,应该是一组参数,然后给出一组参数中的最大值,而不是给出指定数组的最大值,所以:

Math.max(3, 4, 5); // 返回5
Math.max.call(null, 3, 4, 5); // 返回5
Math.max.apply(null, [3, 4, 5]); // 返回5

Math.max([3, 4, 5]); // 返回NaN

  • 1

Reply