arguments並非一個真正的數組,而是一個「相似數組(array-like)」的對象;數組
就像下面的這段輸出,就是典型的類數組對象:函數
{0:12, 1:23}
相同點:spa
不一樣點:prototype
function calc(){ console.log(arguments); // ["sky", "moon", callee: ƒ, Symbol(Symbol.iterator): ƒ] console.log(arguments[0]); // sky console.log(arguments.length); // 2 // arguments.pop(); // 報錯,arguments.pop is not a function } calc('sky', 'moon');
function calc(){ var newArr = Array.prototype.slice.call(arguments); newArr.pop(); console.log(newArr); // ["sky"] } calc('sky', 'moon');
好比咱們要實現:一個參數時,作乘法運算;二個參數時,作加法運算;code
看下面代碼,咱們能夠這樣實現:對象
// 實現重載(overload) function calc(){ //傳1個參數,求平方 if(arguments.length == 1){ return arguments[0] * arguments[0]; } //傳2個參數,求和 else if(arguments.length == 2){ return arguments[0] + arguments[1]; } } console.log(calc(5));//25 console.log(calc(12,23));//35
首先咱們用最原始的方法,實現數字的疊加blog
function calc(num){ if(num <= 0){ return 0; }else{ return num += calc(num - 1); } } console.log(calc(3)); // 6
而後咱們用類數組來實現一樣的功能:遞歸
arguments.callee:返回當前函數自己
function calc(num){ if(num <= 0){ return 0; }else{ return num += arguments.callee(num - 1); } } console.log(calc(3)); // 6
下面舉個栗子,來講明這兩種調用的一點小區別:it
若是寫成 return num += calc(num - 1) 會報錯;緣由很簡單,當執行calc = null 後,calc已經不是一個函數;io
可是寫成 return num += arguments.callee(num - 1) 不會報錯;由於arguments.callee指的是「當前函數」,並非「calc」
function calc(num){ console.log(arguments); if(num <= 0){ return 0; }else{ return num += arguments.callee(num - 1); // return num += calc(num - 1); // 報錯 Uncaught TypeError: calc is not a function } } var result = calc; calc = null; console.log(result(3));
Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
"use strict"; function calc(num){ if(num <= 0){ return 0; }else{ return num += arguments.callee(num - 1); } } console.log(calc(3));