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 等效啦
// 以下(遍历器生成)函数返回一个 iterator 对象
function makeIterator(array) {
var nextIndex = 0;
return {
next: function() {
return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{done: true};
}
};
}
var it = makeIterator(['yo', 'ya']);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done); // true
如果一个对象具有 [Symbol.iterator] 属性,且该属性的值为一个遍历器生成函数,则这个对象就是 iterable 的:
class SimpleClass {
constructor(data) {
this.index = 0;
this.data = data;
}
[Symbol.iterator]() {
return {
next: () => {
if (this.index < this.data.length) {
return {value: this.data[this.index++], done: false};
} else {
this.index = 0; //If we would like to iterate over this again without forcing manual update of the index
return {done: true};
}
}
};
}
}
const simple = new SimpleClass([1,2,3,4,5]);
for (const val of simple) {
console.log(val); //'1' '2' '3' '4' '5'
}