arguments函数
- 运用形参时,大多是不知道实参会返回有多少个实际参数代入形参的,使用arguments函数,会自动调整实参的数量代入形参中使用,也就是说,可以获取所有实际传递的参数。
- arguments函数是所有非箭头函数中都可以使用的局部变量,是一个类似数组的对象,你可以使用在函数中引用函数的实际参数
- arguments参数是传入函数的所有参数的集合,具有lenght属性,表示传入参数的个数,通过arguments参数还可以获取那些与函数形参不匹配的参数。在非严格模式下,arguments对象是函数参数的别名,修改arguments对象会修改函数实参,可以通过严格模式避免修改函数实参
arguments函数调用
实例:
function add(){
var sum = 0;
console.log(arguments)
//调用arguments函数,接收add实参数量
for(var i = 0;i<arguments.lenght;i++){
sum = sum + arguments[i]
}
return sum
}
var result = add(1,2,3,4,5,6,7,8)
//add执行的结果返回result中
console.log(result)
//随后执行输出result结果
实操图:
网页输出结果为:
转化为真数组:
1:slice
arguments对象不支持数组的其他方法,但是可以用function.call来间接调用
function add(){
console.log(Array.prototype.slice.call(argument,0));
}
add("hello","你好","shijie")
2:splice
function add(){
console.log(Array.prototype.splice.call(arguments,0));
}
add("hello","你好","shijie")
3:Array.from
function add(){
console.log(Array.from(arguments));
}
add("hello","你好","shijie")
4:扩展运算符
function add(...arguments){
console.log(arguments);
}
add("hello","你好","shijie")
严格模式
- 严格模式和非严格模式中,arguments的表示显示不相同。
- 在非严格模式中,传入的参数,实参和arguments的值会被共享,当没有传入时,实参与arguments值不会共享。而在严格模式中,实参和arguments的值不会共享。
PS:欢迎观看,最后希望文章对你有所帮助!