arguments
Description
在全部的函数中有一个arguments对象,arguments对象指向函数的参数,arguments object is an Array-like object,除了length,不具有数组的其余属性。
访问: var a = arguments[0];
arguments能够改变: arguments[1] = 'new value';
arguments转换为一个真实的数组:
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
var args = Array.from(arguments);
var args = [...arguments];数组
Properties
arguments.callee
Reference to the currently executing function.
指向当前正在执行的函数的函数体。在匿名函数中颇有用。函数
function fun(){ console.log(arguments.callee == fun);//true console.log(arguments.callee); /* function fun(){ console.log(arguments.callee == fun);//true console.log(arguments.callee); } */ } fun();
var global = this; var sillyFunction = function(recursed) { if (!recursed) { return arguments.callee(true); } if (this !== global) { console.log('This is: ' + this); } else { console.log('This is the global'); } } sillyFunction();//This is: [object Arguments]
使用arguments.callee在匿名递归函数中:
一个递归函数必须可以指向它本身,经过函数名能够指向本身,可是在匿名函数没有函数名,因此使用arguments.callee指向本身。this
function create() { return function(n) { if (n <= 1) return 1; return n * arguments.callee(n - 1); }; } var result = create()(5); console.log(result);// returns 120 (5 * 4 * 3 * 2 * 1)
arguments.caller
Reference to the function that invoked the currently executing function.这个属性已经被移出了,再也不工做,可是仍然能够使用Function.caller.spa
function whoCalled() { if (arguments.caller == null) console.log('I was called from the global scope.'); else console.log(arguments.caller + ' called me!'); } whoCalled();//I was called from the global scope.
function whoCalled() { if (whoCalled.caller == null) console.log('I was called from the global scope.'); else console.log(whoCalled.caller + ' called me!'); } whoCalled();//I was called from the global scope.
function whoCalled() { if (whoCalled.caller == null) console.log('I was called from the global scope.'); else console.log(whoCalled.caller + ' called me!'); } function meCalled(){ whoCalled(); } meCalled(); /* function meCalled(){ whoCalled(); } called me! */
arguments.length
Reference to the number of arguments passed to the function.
arguments[@@iterator]
Returns a new Array Iterator object that contains the values for each index in the arguments.prototype
Examplescode
function myConcat(separator) { var args = Array.prototype.slice.call(arguments, 1); return args.join(separator); } myConcat(', ', 'red', 'orange', 'blue');// returns "red, orange, blue" function bar(a = 1) { arguments[0] = 100; return a; } bar(10); // 10 function zoo(a) { arguments[0] = 100; return a; } zoo(10); // 100