JavaScript 函数应用
apply()方法使用给定的this值调用一个函数,并以数组(或类似数组的对象)的形式提供参数。
letnumbers=[5,6,2,3,7];letmax=Math.max.apply(null,numbers);document.write(max);测试看看‹/›
call()和apply()之间的区别
call()方法单独接受参数。
apply()方法将参数作为数组。
如果要使用数组而不是参数列表,则apply()方法非常方便。
使用apply()和内置函数
巧妙地使用,apply()您可以将内置函数用于某些任务,否则可能是通过遍历数组值来编写的。
作为示例,我们将使用Math.max/ Math.min来找出数组中的最大值/最小值。
letnumbers=[5,6,2,3,7];letmax=Math.max.apply(null,numbers);letmin=Math.min.apply(null,numbers);for(leti=0;i<numbers.length;i++){if(numbers[i]>max){max=numbers[i];}if(numbers[i]<min){min=numbers[i];}}document.write(min,"<br>",max);测试看看‹/›
使用apply()调用函数而不指定参数
在下面的示例中,我们在不传递参数的情况下调用了display函数:
varname="Seagull";functiondisplay(){document.write(this.name);}display.apply();测试看看‹/›
编辑于2024-06-05 09:10