const endpoint = ‘https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json‘;
const search = document.querySelector(‘.search’);
const suggestions = document.querySelector(‘.suggestions’);
search.addEventListener(‘keyup’, displayMatch);
search.addEventListener(‘change’, displayMatch);
const cities = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => cities.push(…data));

function findMatch(wordToMatch, data) {
const regexp = new RegExp(wordToMatch, ig)
return data.filter( place => {
return place.city.match(regexp) || place.state.match(regexp);
})
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ‘,’);
}
function displayMatch() {
// this.value is a string
const matchedList = findMatch(this.value, cities);
const matchedListHTML = matchedList.map(place => {
const regexp = new RegExp(this.value, ‘ig’);
const city = place.city.replace(regexp, <span class='hl'>${this.value}</span>);
const state = place.state.replace(regexp, <span class='hl'>${this.value}</span>);
return <br /> <li><br /> <span class='name'>${city}, ${state}</span><br /> <span class='population'>${numberWithCommas(place.population)}</span><br /> </li><br />;
}).join(‘’);
suggestions.innerHTML = matchedListHTML;


iterator 是对象,是一种满足特定条件的对象

generator 就是一个能够自动返回 iterator 的函数。一个普通的函数,只要能返回 iterator,那么它的作用和 generator 等效啦

image.png

  1. // 以下(遍历器生成)函数返回一个 iterator 对象
  2. function makeIterator(array) {
  3. var nextIndex = 0;
  4. return {
  5. next: function() {
  6. return nextIndex < array.length ?
  7. {value: array[nextIndex++], done: false} :
  8. {done: true};
  9. }
  10. };
  11. }
  12. var it = makeIterator(['yo', 'ya']);
  13. console.log(it.next().value); // 'yo'
  14. console.log(it.next().value); // 'ya'
  15. console.log(it.next().done); // true

如果一个对象具有 [Symbol.iterator] 属性,且该属性的值为一个遍历器生成函数,则这个对象就是 iterable 的:

  1. class SimpleClass {
  2. constructor(data) {
  3. this.index = 0;
  4. this.data = data;
  5. }
  6. [Symbol.iterator]() {
  7. return {
  8. next: () => {
  9. if (this.index < this.data.length) {
  10. return {value: this.data[this.index++], done: false};
  11. } else {
  12. this.index = 0; //If we would like to iterate over this again without forcing manual update of the index
  13. return {done: true};
  14. }
  15. }
  16. };
  17. }
  18. }
  19. const simple = new SimpleClass([1,2,3,4,5]);
  20. for (const val of simple) {
  21. console.log(val); //'1' '2' '3' '4' '5'
  22. }

第一次调用 generator 函数时并不会运行它,而是会返回一个iterator 对象:

image.png

image.png

How to create a fake Async

image.png
image.png