We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
javascript 中函数的arguments 是一个类似数组对象
arguments 的length属性代表的是函数实际接收的参数,如果想获取函数期望获取的参数可以使用函数名.length来获取。
function demo(a, b, c) { var t = arguments.length var e = demo.length console.log(t) console.log(e) } demo(1, 2) demo(1, 2, 3) demo(1, 2, 3, 4)
运行结果:
arguments.caller 属性指向函数本身
function demo(a, b, c) { console.log(arguments.callee) } demo()
运行结果:
arguments.callee 指向调用当前函数的函数
function a() { if (a.caller) { var caller = a.caller.toString() console.log(caller) } else { console.log('none') } } function b() { a() } function c() { b() } a() b() c()
arguments对象不是一个 Array,它是一个类数组对象,它除了length属性外没有其他的数组属性和方法,但是我们可以通过以下方法将arguments对象转换成一个真正的数组
var args = Array.prototype.slice.call(arguments) var args = [].slice.call(arguments) var args = Array.from(arguments) var args = [...arguments] var args = ( arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) ) var args = Array.slice(arguments)
var demo = (function(num) { if (num <= 1) { return 1 } else { return num * arguments.callee(num - 1) } })(5) console.log(demo)
我们可以根据传入参数的数量的不同做不同的操作。
function demo() { var length = arguments.length for (var i = 0; i < length; i++) { if (typeof arguments[i] !== 'number') return } switch (length) { case 1: console.log('操作1') break case 2: console.log('操作2') break case 3: console.log('操作3') break } } demo(1) demo(1, 2) demo(1, 2, 3)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
javascript 中函数的arguments 是一个类似数组对象
属性
1. length属性
arguments 的length属性代表的是函数实际接收的参数,如果想获取函数期望获取的参数可以使用函数名.length来获取。
运行结果:
2. callee属性
arguments.caller 属性指向函数本身
运行结果:
3. caller属性
arguments.callee 指向调用当前函数的函数
运行结果:
转换成数组
arguments对象不是一个 Array,它是一个类数组对象,它除了length属性外没有其他的数组属性和方法,但是我们可以通过以下方法将arguments对象转换成一个真正的数组
应用
1. 利用arguments.callee 实现递归调用
运行结果:
2. 实现方法的重载,参数不定长
我们可以根据传入参数的数量的不同做不同的操作。
参考资料
The text was updated successfully, but these errors were encountered: