# 2.2 Array 操作方法

* **Array.forEach(function(element) {})**

  將陣列內的元素抓取出來，並可對其操作。

  ```
  var arr = [1, 2, 3];
  arr.forEach(function(element) {
    console.log(element);    // 1 2 3
  });
  ```
* **Array.map(function(element) {})**

  將陣列內的元素抓取出來，並可對其操作，並在function執行結束後回傳一個新的陣列。

  ```
  var arr = [1, 2, 3];
  var arr2 = arr.map(function(element) {
    return element * 2;
  });
  console.log(arr);    // [1, 2, 3]
  console.log(arr2);   // [2, 4, 6]
  ```
* **Array.filter(function(element) {})**

  過濾陣列內的元素，並回傳過濾後的新陣列。

  ```
  var arr = [1, 2, 3];
  var arr2 = arr.filter(function(element) {
    return element < 3;
  });
  console.log(arr2);     // [1, 2]
  ```
* **Array.reduce(function(accumulator, currentValue) {})**

  將陣列內的元素全部加總。
* ```
  var arr = [1, 2, 3];
  var sum = arr.reduce(function(accumulator, currentValue) {
    // accumulator 前一個回傳值
    return accumulator += currentValue;
  });
  console.log(sum);    // 6
  ```
* **Array.indexOf(element)**

  抓取陣列內元素的index。

  ```
  var arr = [1, 2, 3];
  var index = arr.indexOf(1);
  console.log(index);     // 0
  ```


---

# Agent Instructions: 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:

```
GET https://jack1in.gitbook.io/font-end/2.-javascript/2.2-array-cao-zuo-fang-fa.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
