使用apply调用函数
生活随笔
收集整理的這篇文章主要介紹了
使用apply调用函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
實現函數 callIt,調用之后滿足如下條件
1、返回的結果為調用 fn 之后的結果
2、fn 的調用參數為 callIt 的第一個參數之后的全部參數
代碼
?
1 /*因為arguments并非真正的數組,因此要獲得callIt的第一個參數之后的所有參數, 2 不能直接使用slice方法截取,需要先將arguments轉換為真正的數組才行*/ 3 //方法一:使用slice方法:var args = Array.prototype.slice.call(arguments); 4 function callIt(fn) { 5 //將arguments轉化為數組后,截取第一個元素之后的所有元素 6 var args = Array.prototype.slice.call(arguments,1); 7 //或return fn.apply(null.args),因為給apply傳遞null,“”空字符串,默認都是this 8 return fn.apply(this,args); 9 } 10 11 //方法二:for循環 12 function callIt(fn) { 13 var args = new Array(); 14 for(var i=1; i<arguments.length; i++){ 15 args[i-1] = arguments[i]; 16 } 17 return fn.apply(this,args); 18 }?
來源:牛客網
?
?
?
轉載于:https://www.cnblogs.com/daheiylx/p/8900101.html
總結
以上是生活随笔為你收集整理的使用apply调用函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python常用模块——目录
- 下一篇: 数组运用_1-19 编程练习