迭代器和生成器

可迭代的

如果一个对象具有 Symbol.iterator 属性的实现,则该对象被认为是可迭代的。一些内置类型,如 ArrayMapSetStringInt32ArrayUint32Array 等,它们的 Symbol.iterator 属性已经实现。对象上的 Symbol.iterator 函数负责返回要迭代的值列表。

Iterable 接口

如果我们想采用上面列出的可迭代类型,Iterable 是我们可以使用的类型。这是一个例子:

function toArray<X>(xs: Iterable<X>): X[] {
  return [...xs]
}

for..of 语句

for..of 循环遍历一个可迭代对象,调用该对象的 Symbol.iterator 属性。这是一个数组上的简单 for..of 循环:

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

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

for..of 与 for..in 语句

for..offor..in 语句都遍历列表;但是,迭代的值不同,for..in 返回被迭代对象的键列表,而 for..of 返回被迭代对象的数字属性的值列表。

这是一个演示这种区别的示例:

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
}

zWUv1T4imZvATzZjX+nI7qkqJ6mXVY9KMNX9TyUluzvgmwR+uGOxAiLB8yJzi+sNnvGmkeDO2Sxumr0452XYgU7vfFfvpPpQTJ6AkkaVIvgk8YIBakElAhBF8YbHhVqGi90ihp6HMiB/+03ppi1oTm3UcDoH/Si4vvg7/2YVAAuet7LDnyLcy5njBVU/0D68F1qWOrxYQQZREjMJUrmu+xZX18OMl+Ln2ykAqUqauo9QI6gfwbqk6HW6uWannYeiP4mAXXKQKznOA2fOavDc5DyXQquvzsQfXEe0iBG/CwUQPjy1mADqF8ayizv8ORFi9nTeDvdrnCteYMyLTSjapq/tV/RqkezSjvK22jT6a3yrQiXDdd0S/nOqPYS5DOF+Tyvw4avcSP+E9cdYbyYVKmLDlTMp065oHEddP5zAKjJRQVInLPjy3g8Qy0NtZpCgQ5OBzkNIDEqCOMzJtl0ntA==

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"
}

代码生成

针对 ES5 和 ES3

sM/CQUoBm48CYlRwyiHb4ALkYCVw6MnbDOE/wOMiAVw5+E9PBXnZt48w47LEFM0L0yFSNvhZB2hKi96dKjAXMiHes8ElC1AHGfIvkZksLaaEt/lr42QCp3pRJfUSICJFF8T6zyAX++RDf1bBnvWr0OGc2KqLcZek1XtNaBxv55QMwVD/U+gwuccfT303EaebjowKaiDmct+TowgN80tPDrlRBcqLYyI9bceDbZ43FMRqAcP6WKNNXrntFsqf8v3dnJ3xbEPGaL31ZGJSZcrhcFpydGmfLEvrgGGxgvKkBYj1mJo5ATAEOWIDhPWJZxQHVAGmY5xWpd0XS7YZnL/m8A==

mDgwDdnAC3ViXmbZ1lN9rJm24uhtgWRkZghTkbPXw6gKHX2mQp7+EhLyDKx9LWEhinJWpVvhSRzB4qoe+uNEQgan6mI0IiMXHWi185QENRA9pMkAsSxSEvKMCq7JoSQZXU+cZN9klmDfE1JwgWQPVQ==

let numbers = [1, 2, 3];
for (let num of numbers) {
  console.log(num);
}

UTRR+h4H8ktw+OMtMfNVFQ==

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

以 ECMAScript 2015 及更高版本为目标

PjaITqlzOCjNLhCYO7g5uwj2UbiB5HR7l/GuMgYqW8TIsrldhVilIxBSGtyR44/eY5a0hrzIFe2sWDUl66cNNnmKNbJ9zDItbts7NqIXPB7jgBCGWVHDYYVCqV+5RAZJ8bkXJ44khSx1UFui7O3mrB090CT5bzKDy/PJ/1m4x69v4jQaNMEVFa9zNcv01QZl