# Iterator (ok)

Trong pattern này, bạn có một object chứa data có cấu trúc phức tạp, bạn muốn truy cập vào thuộc tính của object này một cách dễ dàng. Người dùng object không cần biết cấu trúc của object, họ chỉ cần làm việc với các thuộc tính riêng lẻ

Trong mô hình này, bạn cần phát triển một method next(),gọi hàm này để lấy phần tử tiếp theo

```
var element;
while (element = agg.next()) {
  // do something with the element ...
  console.log(element);
}
```

Implement iterator pattern như sau

```
var agg = (function() {
  var index = 0,
    data = [1, 2, 3, 4, 5],
    length = data.length;
  return {
    next: function() {
      var element;
      if (!this.hasNext()) {
        return null;
      }
      element = data[index];
      index = index + 1;
      return element;
    },
    hasNext: function() {
      return index < length;
    }
  };
}());
```

Để dễ dàng truy cập data, bạn có thể implement thêm một số method sau

rewind() : reset pointer trở về đầu

current(): trả về phần tử hiện tại

```
var agg = (function() {
  // [snip...]
  return {
    // [snip...]
    rewind: function() {
      index = 0;
    },
    current: function() {
      return data[index];
    }
  };
}());
```


---

# 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://javascriptuse.gitbook.io/javascript/advanced/iterator-ok.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.
