js Arguments对象笔记

1、概念

arguments 是一个对应于传递给函数的参数的类数组对象。
arguments对象是所有(非箭头)函数中都可用的局部变量。你可以使用arguments对象在函数中引用函数的参数。

2、使用

arguments对象不是一个 Array。它类似于Array,但除了length属性和索引元素之外没有任何Array属性。

function demo(a){
 console.log(arguments[0]);
}
demo(); //undefined
demo(1); //1

arguments对象可以转换为数组

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

// ES2015
const args = Array.from(arguments);   //使用Array.from()方法
const args = [...arguments];   //使用扩展运算符

3、属性

arguments.callee   指向当前执行的函数。

arguments.caller (已废弃)指向调用当前函数的函数。

arguments.length  指向传递给当前函数的参数数量。

arguments[@@iterator]   返回一个新的Array迭代器对象,该对象包含参数中每个索引的值。

4、剩余参数、默认参数和解构赋值参数

严格模式下,剩余参数、默认参数和解构赋值参数的存在不会改变 arguments对象的行为

'use strict' //使用严格模式
function func(a) { 
  arguments[0] = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

function func(a) { 
  a = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

function func(a =50) { 
  arguments[0] = 99;
  console.log(a);
}
func(10); // 10

非严格模式中的函数没有包含剩余参数、默认参数和解构赋值参数,那么arguments对象中的值跟踪参数的值,同样参数的值也会跟踪arguments对象中的值

function func(a) { 
  arguments[0] = 99;   // 更新了arguments[0] 同样更新了a
  console.log(a);
}
func(10); // 99

并且

function func(a) { 
  a = 99;              // 更新了a 同样更新了arguments[0] 
  console.log(arguments[0]);
}
func(10); // 99

当非严格模式中的函数包含剩余参数默认参数解构赋值,那么arguments对象中的值不会跟踪参数的值

function func(a = 55) { 
  arguments[0] = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

function func(a = 55) { 
  a = 99; // updating a does not also update arguments[0]
  console.log(arguments[0]);
}
func(10); // 10

function func(a = 55) { 
  console.log(arguments[0]);
}
func(); // undefined

5、参考链接

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值