Các tình nguyện viên của chúng tôi chưa dịch bài viết này thành Tiếng Việt. Tham gia với chúng tôi và hoàn thành công việc!
Bạn cũng có thể đọc bài viết trongEnglish (US).

The Symbol.iterator well-known symbol specifies the default iterator for an object. Used by for...of.

Description

Whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.

Some built-in types have a default iteration behavior, while other types (such as Object) do not. The built-in types with a @@iterator method are:

See also Iteration protocols for more information.

Property attributes of Symbol.iterator
Writable no
Enumerable no
Configurable no

Examples

User-defined iterables

We can make our own iterables like this:

var myIterable = {}
myIterable[Symbol.iterator] = function* () {
    yield 1;
    yield 2;
    yield 3;
};
[...myIterable] // [1, 2, 3]

Or iterables can be defined directly inside a class or object using a computed property:

class Foo {
  *[Symbol.iterator] () {
    yield 1;
    yield 2;
    yield 3;
  }
}

const someObj = {
  *[Symbol.iterator] () {
    yield 'a';
    yield 'b';
  }
}

[...new Foo] // [ 1, 2, 3 ]
[...someObj] // [ 'a', 'b' ]

Non-well-formed iterables

If an iterable's @@iterator method does not return an iterator object, then it is a non-well-formed iterable. Using it as such is likely to result in runtime exceptions or buggy behavior:

var nonWellFormedIterable = {}
nonWellFormedIterable[Symbol.iterator] = () => 1
[...nonWellFormedIterable] // TypeError: [] is not a function

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Symbol.iterator' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Symbol.iterator' in that specification.
Draft

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
iteratorChrome Full support 43Edge Full support 12Firefox Full support 36IE No support NoOpera Full support 30Safari Full support 10WebView Android Full support 43Chrome Android Full support 43Firefox Android Full support 36Opera Android Full support YesSafari iOS Full support 10Samsung Internet Android Full support Yesnodejs Full support 0.12

Legend

Full support  
Full support
No support  
No support

See also

Document Tags and Contributors

Những người đóng góp cho trang này: chrisdavidmills, 1hko, mdnwebdocs-bot, fscholz, mfuji09, wbamberg, liam4, jameshkramer, kdex, mhthompson86, DevelX
Cập nhật lần cuối bởi: chrisdavidmills,