JavaScript Array [Symbol.iterator]() Method

Array 对象参考手册JavaScript Array Object


Example

Get the iterator object of an array and output it in a loop:

const fruits = ['apple', 'banana', 'orange']; //1. Get the iterator object of the array const iterator = fruits[Symbol.iterator](); //2. Manually call the iterator's next() method console.log(iterator.next()); // { value: 'apple', done: false } console.log(iterator.next()); // { value: 'banana', done: false } console.log(iterator.next()); // { value: 'orange', done: false } console.log(iterator.next()); // { value: undefined, done: true } //3. Use the for...of loop (it automatically calls [Symbol.iterator]() internally) for (const fruit of fruits) { console.log(fruit); } //Output: // apple // banana // orange //4. Use the spread operator (also relies on the iterator) const fruitCopy = [...fruits]; console.log(fruitCopy); // ['apple', 'banana', 'orange']

Try it Yourself »

Definition and Usage

[Symbol.iterator]()It is a built-in method of JavaScript arrays, returning the default iterator of the array. This method makes the array an iterable object, which can befor...ofused by loops and other constructs.

What is an Iterator?

Before we explain[Symbol.iterator]()the method, we need to first understand what an iterator is.

An iterator is a protocol in JavaScript that defines how to sequentially access the elements of a collection. Any object that implements the iterator protocol can befor...ofloops, the spread operator (...) and other JavaScript features.

An iterator object must implement anext()method, which returns an object containing two properties:

  • value: the value of the current iteration
  • done: a boolean indicating whether iteration is complete

Basic Syntax

const iterator = array[Symbol.iterator]();

Example Code

Let's look at a simple example:

Example

const fruits = ['apple', 'banana', 'orange'];

// Get the iterator of the array
const iterator = fruits[Symbol.iterator]();

console.log(iterator.next()); // { value: 'apple', done: false }
console.log(iterator.next()); // { value: 'banana', done: false }
console.log(iterator.next()); // { value: 'orange', done: false }
console.log(iterator.next()); // { value: undefined, done: true }

In this example, we:

  1. created an array containing three fruits
  2. through[Symbol.iterator]()method, obtained the array's iterator
  3. Repeatedly call the iterator'snext()method to get each element of the array in turn.

Practical Application Scenarios

1. Using the for...of Loop

for...ofThe loop internally automatically calls the array's[Symbol.iterator]()method:

Example

const colors = ['red', 'green', 'blue'];

for (const color of colors) {
  console.log(color);
}
// Output:
// red
// green
// blue

2. Using the Spread Operator

The spread operator also relies on the iterator protocol:

Example

const numbers = [1, 2, 3];
const copiedNumbers = [...numbers];

console.log(copiedNumbers); // [1, 2, 3]

3. Destructuring Assignment

Array destructuring also uses the iterator:

Example

const [first, second] = ['a', 'b', 'c'];
console.log(first); // 'a'
console.log(second); // 'b'

Customizing Array Iteration Behavior

Although rarely needed, you can override the array's default[Symbol.iterator]()method to customize iteration behavior:

Example

const customArray = [1, 2, 3];

customArray[Symbol.iterator] = function() {
  let index = this.length;
 
  return {
    next: () => {
      index--;
      return {
        value: this[index],
        done: index < 0
      };
    }
  };
};

for (const num of customArray) {
  console.log(num);
}
// Output:
// 3
// 2
// 1

In this example, we modified the iterator so that the array iterates from back to front.


Comparison with Other Iteration Methods

Differences from forEach()

  • forEach()is an array method that executes a callback function for each element
  • [Symbol.iterator]()returns an iterator object, allowing more flexible control over the iteration process

Relationship with keys()/values()/entries()

These methods all return iterators, but they have different uses:

  • keys(): returns an iterator for the array indices
  • values(): returns an iterator for the array elements (same as[Symbol.iterator]())
  • entries(): returns an iterator for index/value pairs

Browser Compatibility

Array [Symbol.iterator]()The method is supported in the following environments:

  • Chrome 38+
  • Firefox 36+
  • Edge 12+
  • Safari 9+
  • Opera 25+
  • Node.js 0.12+

Summary

Array [Symbol.iterator]()The method is key to JavaScript arrays implementing the iterable protocol. Understanding how this method works can help you:

  1. Gain a deeper understanding of JavaScript's iteration mechanism
  2. Write more efficient iteration code
  3. Customize iteration behavior when needed

Remember, in most cases you don't need to call this method directly, becausefor...ofloops and other language features handle it internally. But understanding how it works will make you a better JavaScript developer.

Array 对象参考手册JavaScript Array Object

Other Extensions