> For the complete documentation index, see [llms.txt](https://anjia1.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://anjia1.gitbook.io/web/js/data-type/object/function/param.md).

# 1.4.2 函数参数

开始

## 6. 使用 arguments 对象

函数的参数保存在一个类数组对象中。 在函数里，我们可以使用 `arguments[i]` 来获取传递给它的参数， 其中 i 是参数的序号，值从 0 开始。所以，传递给函数的第一个参数就是 `arguments[0]`，参数的总数用 `arguments.length` 来表示。

使用 arguments 对象，我们可以使用比声明参数更多的参数来调用函数。比如：

```javascript
// 函数定义：函数声明
function myConcat(separator) {
  let result = "";
  // 使用 arguments 对象
  for (let i = 1; i < arguments.length; i++) {
    result += arguments[i] + separator;
  }
  return result;
}
// 函数调用
myConcat(", ", "red", "orange", "blue");
myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
```

注意：变量 arguments 是“类”数组而不是数组，因为它只具有有序索引 `[i]` 和 length 属性，而不具备所有的数组操作方法。

## 7. 函数参数

有两种特殊的参数语法：

* default parameters，默认参数
* rest parameters，剩余参数

### 7.1 默认参数

在 JavaScript 中，函数参数的默认值是 undefined。但在某些情况下，设置不同的默认值可能会更有用，这正是默认参数的用途。

之前，给参数设置默认值的方法通常是在函数体里判断参数值，如果它是 undefined，那就给它赋个新值。比如：

```javascript
function multiply(a, b) {
  b = typeof b !== "undefined" ? b : 1;
  return a * b;
}

multiply(5); // 5
```

有了默认参数的语法，就不需要再手动检查了，可以直接这样写：

```javascript
function multiply(a, b = 1) {
  return a * b;
}

multiply(5); // 5
```

### 7.2 剩余参数

剩余参数的语法，允许我们将不定数量的参数表示成一个数组。比如：

```javascript
// 这里用剩余参数收集从第二个到结尾的参数
function multiply(multiplier, ...theArgs) {
  return theArgs.map(x => multiplier * x);
}

const arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]
```

##


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://anjia1.gitbook.io/web/js/data-type/object/function/param.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
