LoginSignup
3
5

More than 5 years have passed since last update.

TypeScript Handbook を読む (12. Iterators and Generators)

Last updated at Posted at 2017-04-25

TypeScript Handbook を読み進めていく第十二回目。

  1. Basic Types
  2. Variable Declarations
  3. Interfaces
  4. Classes
  5. Functions
  6. Generics
  7. Enums
  8. Type Inference
  9. Type Compatibility
  10. Advanced Types
  11. Symbols
  12. Iterators and Generators (今ココ)
  13. Modules
  14. Namespaces
  15. Namespaces and Modules
  16. Module Resolution
  17. Declaration Merging
  18. JSX
  19. Decorators
  20. Mixins
  21. Triple-Slash Directives
  22. Type Checking JavaScript Files

Iterators and Generators

原文

Iterables

Symbol.iterator プロパティを持つオブジェクトは反復可能なオブジェクトとして扱われます。

for..of statements

for...of はオブジェクトの持つ Symbol.iterator プロパティを使用してループを行います。

TypeScript
let someArray = [1, "string", false];

for (let entry of someArray) {
    console.log(entry); // 1, "string", false
}

for..of vs. for..in statements

for..offor..in はともにリストをループしますが、for..in はオブジェクトの キー のリストを返却するのに対し、for..of は数値インデックスで参照できる を返却する点が異なります。

TypeScript
let list = [4, 5, 6];

for (let i in list) {
   console.log(i); // "0", "1", "2",
}

for (let i of list) {
   console.log(i); // "4", "5", "6"
}

それ以外に、for..in は任意のオブジェクトの持つプロパティを検査する目的で使用されるのに対し、for..of は反復対象のオブジェクトの持つ値に焦点を当てている点が異なります。
MapSet のような組み込み型は格納している値を参照するための Symbol.iterator を持っています。

TypeScript
let pets = new Set(["Cat", "Dog", "Hamster"]);
pets["species"] = "mammals";

for (let pet in pets) {
   console.log(pet); // "species"
}

for (let pet of pets) {
    console.log(pet); // "Cat", "Dog", "Hamster"
}

Code generation

Targeting ES5 and ES3

ES5 または ES3 を対象としている場合、反復対象とできるのは Array のみです。
それ以外の型を対象とした場合、それが Symbol.iterator を実装していたとしてもエラーとなります。

この時、コンパイラは for..of から単純な for ループを生成します。

TypeScript
let numbers = [1, 2, 3];
for (let num of numbers) {
    console.log(num);
}
JavaScript
var numbers = [1, 2, 3];
for (var _i = 0; _i < numbers.length; _i++) {
    var num = numbers[_i];
    console.log(num);
}

Targeting ECMAScript 2015 and higher

ECMAScipt 2015 を対象としている場合、ネイティブの for..of を使用するコードが生成されます。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5