概述
JS Arguments的主要特点
- 当参数的个数不确定时,可以用arguments来获取。arguments对象中存储了传递的所有实参。
- arguments对象是所有(非箭头)函数中都可用的局部变量。
- arguments对象是一个伪数组. 除了length和索引外,不能用任何数组的方法。
- 可以使用arguments对象在函数中引用函数的参数,索引从0开始。
function func(){
console.log(arguments)//Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
}
func(1,2,3)
一定要注意,arguments是存储传递的所有实参,默认参数是不会存储的
function func(firstArg = 0, secondArg = 1, thirdArg = 2) {
console.log(arguments[0], arguments[1], arguments[2]);//10 undefined undefined
console.log(firstArg, secondArg, thirdArg);//10 1 2
}
func(10);
Arguments转真实数组
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
// ES2015
const args = Array.from(arguments);
const args = [...arguments];
callee获取当前arguments所在的函数
注意:Arguments.callee()可以调用函数本身当函数正在执行时才可调用,可以实现方法的递归调用。Arguments.callee是代表当前函数,但是不会调用。
function func() {
console.log("获取当前所在的函数");
console.log(arguments.callee)
}
func()
打印结果如下:
通过Arguments.callee()实现递归求和(严格模式下不能使用)
var sum = function(n) {
if (n == 1) {
return 1;
} else {
return n + arguments.callee(n - 1);
}
}
console.log("sum =", sum(5));//15
Arguments使用案例
a.求任意个数数字的最大值
function getMax() {
console.log(arguments);
let max = arguments[0];
for (var i = 1; i <= arguments.length; i++) {
max = arguments[i] > max ? arguments[i] : max;
}
return max;
}
console.log(getMax(11, 22, 5));//22
console.log(getMax(11, 22, 13, 23, 4, 5));//23
arguments与剩余参数、默认参数和解构赋值参数的结合使用
①当非严格模式中的函数没有包含剩余参数、默认参数和解构赋值,那么arguments
对象中的值会跟踪参数的值。
function func1(a) {
arguments[0] = 99; // 更新了arguments[0] 同样更新了a
console.log(a);// 99
}
func1(100);
// 并且
function func2(a) {
a = 99; // 更新了a 同样更新了arguments[0]
console.log(arguments[0]); // 99
}
func2(100);
②严格模式下的函数没有包含剩余参数、默认参数和解构赋值,那么arguments
对象中的值也不会跟踪参数的值。
function func1(a) {
'use strict';
arguments[0] = 99; // 不会更新arguments[0] 也不会更新a
console.log(a);// 100
}
func1(100);
// 并且
function func2(a) {
'use strict';
a = 99; // 不会更新a 也不会更新arguments[0]
console.log(arguments[0]); // 100
}
func2(100);
③当非严格模式中的函数包含剩余参数、默认参数和解构赋值,那么arguments
对象中的值不会跟踪参数的值。(这里以包含默认参数做示范)
function func1(a = 2) {
arguments[0] = 99; // 不会更新arguments[0] 也不会更新a
console.log(a);// 100
}
func1(100);
// 并且
function func2(a = 2) {
a = 99; // 不会更新a 也不会更新arguments[0]
console.log(arguments[0]); // 100
}
func2(100);
最后
以上就是平淡画笔为你收集整理的JS Arguments的使用的全部内容,希望文章能够帮你解决JS Arguments的使用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复