JavaScript之arguments

函数 arguments 对象是所有(非箭头)函数中都可用的局部变量, 是一个类似数组的对象。你可以使用 arguments 对象在函数中引用函数的(实际)参数。

function foo() {
  console.log(arguments);
}

foo(1, "foo", false, { name: "bar" }); // [1, "foo", false, object]
预览
function foo() {
  console.log(typeof arguments);
}

foo(1, "foo", false, { name: "bar" }); // object在这里插入代码片
所以,arguments 是一个具有数组样式的对象,有 length 属性,和下标来索引元素。

arguments 的属性

length

function foo(num1, num2, num3) {
  console.log(arguments);
}

foo(1); // [1]

length 属性表示传入函数的实际参数数量,而不是函数声明时的形参数量。

callee
callee 表示函数本身,我们可以在函数中通过 callee 调用本身。

转化为真数组

slice

arguments 对象不支持数组的其他方法,但是可以用 Function.call 来间接调用。

function sayHi() {
  console.log(Array.prototype.slice.call(arguments, 0));
}
sayHi("hello", "你好", "bonjour"); //["hello", "你好", "bonjour"]
  1. splice
function sayHi() {
  console.log(Array.prototype.splice.call(arguments, 0));
}
sayHi("hello", "你好", "bonjour"); //["hello", "你好", "bonjour"]
  1. Array.from
function sayHi() {
  console.log(Array.from(arguments));
}
sayHi("hello", "你好", "bonjour"); //["hello", "你好", "bonjour"]
  1. 扩展运算符
function sayHi(...arguments) {
  console.log(arguments);
}
sayHi("hello", "你好", "bonjour"); //["hello", "你好", "bonjour"]

五、严格模式

严格模式和非严格模式中,arguments 的表现显示不相同。

// 严格模式
function foo(a, b) {
    "use strict";
    console.log(a, arguments[0]);
    a = 10;
    console.log(a, arguments[0]);
    arguments[0] = 20;
    console.log(a, arguments[0]);
    b = 30;
    console.log(b, arguments[1])
}
foo(1);
输出:
1 1
10 1
10 20
30 undefined

// 非严格模式
function foo(a, b) {
    console.log(a, arguments[0]);
    a = 10;
    console.log(a, arguments[0]);
    arguments[0] = 20;
    console.log(a, arguments[0]);
    b = 30;
    console.log(b, arguments[1]);
}
foo(1);
输出:
1 1
10 10
20 20
30 undefined

在非严格模式中,传入的参数,实参和 arguments 的值会共享,当没有传入时,实参与 arguments 值不会共享。

而在严格模式中,实参和 arguments 的值不会共享。


作者:谢南波
链接:https://www.imooc.com/article/260365
来源:慕课网
本文原创发布于慕课网 ,转载请注明出处,谢谢合作

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值