JavaScript中arguments函数有什么用

发布时间:2021-01-18 11:31:49 作者:小新
来源:亿速云 阅读:171

这篇文章给大家分享的是有关JavaScript中arguments函数有什么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

概述

JavaScript中的函数与其他面向对象语言有几个不同的地方。

  1. 没有函数重载

  2. 有一个表示实参列表的类数组对象 arguments

一、函数重载

简单来说,JAVA 同一个类中允许几个函数有同样的函数名称,但是参数声明不一样,这就是函数重载。

但是 JS 不支持函数重载:

function foo(num) {
    console.log(num + 100)
}
function foo(num) {
    console.log(num + 200)
}

foo(100);  // 300

如果 js 中定义了两个相同名称的函数,那么该名字只属于后定义的那个函数。

二、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 属性,和下标来索引元素。

JavaScript中arguments函数有什么用

三、arguments 的属性

length

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

foo(1);  // [1]

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

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

四、转化为真数组
  1. 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 的值不会共享。

感谢各位的阅读!关于“JavaScript中arguments函数有什么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. JavaScript中Generator函数有什么用
  2. Javascript中arguments对象有什么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript arguments函数

上一篇:java对象如何转换为xml格式

下一篇:使用JavaScript的BOM的注意事项有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》