arguments不是真正的数组,它是一个实参对象,每一个实参对象都包含以数字为索引的一组元素以及length属性。数组
(function () { console.log(arguments instanceof Array); // false console.log(typeof (arguments)); // object })();
只有函数被调用时,arguments对象才会建立,未调用时其值为null函数
console.log(new Function().arguments); // null
当调用函数的时候传入的实参比形参个数少时,剩下的形参都被设置为undefined。.net
给被省略的参数赋值:code
function getPropertyNames(o, /* optional */ a) { a = a || []; // 等于 if(a == undefined) a = []; for (var property in o) { a.push(property); } return a; } console.log(getPropertyNames({ '1': 'a', '2': 'b' })); // ["1", "2"] console.log(getPropertyNames({ '1': 'a', '2': 'b' }, ['3'])); // ["3", "1", "2"]
验证明参的个数对象
function f(x, y, z) { // 首先,验证传入实参的个数是否正确 if (arguments.length != 3) { throw new Error("function f called with " + arguments.length + "arguments, but it expects 3 arguments."); } // 再执行函数的其余逻辑 } f(1, 2); // Uncaught Error: function f called with 2arguments, but it expects 3 arguments.
查看实参和形参的个数是否一致blog
// 查看实参和形参的个数是否一致 function add(a, b) { var realLen = arguments.length; console.log("realLen:", arguments.length); // realLen: 5 var len = add.length; console.log("len:", add.length); // len: 2 if (realLen == len) { console.log('实参和形参个数一致'); } else { console.log('实参和形参个数不一致'); } }; add(1, 2, 3, 6, 8);
模拟函数重载递归
function doAdd() { if (arguments.length == 1) { console.log(arguments[0] + 5); } else if (arguments.length == 2) { console.log(arguments[0] + arguments[1]); } }
接受任意数量的实参,并返回其中的最大值索引
function max(/* ... */) { var max = Number.NEGATIVE_INFINITY; // 遍历实参,查找并记住最大值 for (var i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } // 返回最大值 return max; } console.log(max(1, 10, 110, 2, 3, 5, 10000, 100)); // 10000
自动更新ip
function f(x) { console.log(x); // 1,输出实参的初始值 arguments[0] = null; // 修改实参数组的元素一样会修改x的值 console.log(x); // null x = 'a'; // 修改x的值一样会修改实参数组的元素 console.log(arguments[0]); // a } f(1);
查看callee和caller属性get
function a() { console.log('a...'); b(); } function b() { console.log('b...'); console.log(b.arguments.callee); console.log(b.caller); } a();
经过callee实现递归调用自身
var factorial = function (x) { if (x <= 1) { return 1; } return x * arguments.callee(x - 1); } console.log(factorial(5)); // 120