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));