在遍历数据结构的过程中,有当前被迭代元素的引用,然后把当前的元素返回出来。而且还知道当前元素移动下一个元素。还知道没有元素向下移动时,状态会为 Done 完成。
class Creature {
constructor() {
// this.strength = this.agility = this.intelligence = 10;
this.stats = new Array(3).fill(10);
}
get strength() {
return this.stats[0];
}
set strength(value) {
this.stats[0] = value;
}
get agility() {
return this.stats[0];
}
set agility(value) {
this.stats[1] = value;
}
get intelligence() {
return this.stats[0];
}
set intelligence(value) {
this.stats[2] = value;
}
/*get sumOfStats() {
return this.strength + this.agility + this.intelligence;
}
get averageStat() {
return this.sumOfStats / 3;
}
get MathStat() {
return Math.max(this.strength, this.agility, this.intellience);
}*/
get sumOfStats() {
return this.stats.reduce((x, y) => x + y, 0);
}
get averageStat() {
return this.sumOfStats / this.stats.length;
}
get MathStat() {
return Math.max(...this.stats);
}
}
let creature = new Creature();
creature.strength = 20;
creature.agility = 30;
creature.intellience = 40;
console.log(`这个生物它的数据总和为${creature.sumOfStats}, ` +
`数据的平均值为${creature.avgerageStat}, ` +
`数据中的最大值为${creature.maxStat}`);
ES6 Generator * 是官方迭代器模式的实现 Symbol.iterator
let values = [100, 200, 300];
for (let i in values) {
console.log(`在第${i}位置的元素:${value[i]}`);
}
for (let v of values) { // 使用 Symbol.iterator 进行 遍历
console.log(`值为${v}`);
}
class Stuff {
constructor() {
this.a = 10;
this.b = 100;
}
[Symbol.iterator]() {
let i = 0;
let self = this;
return {
next: function() {
return {
done: i > 1,
value: self[i++ === 0 ? 'a' : 'b']
}
}
}
}
get backwards() {
let i = 0;
let self = this;
return {
next: function() {
return {
done: i > 1,
value: self[i++ === 0 ? 'b' : 'a']
}
},
[Symbol.iterator]: function() {
return this;
}
}
}
}
let stuff = new Stuff();
for (let v of stuff) {
console.log(`值为${v}`);
}
for (let v of stuff.backwards) {
console.log(`值为${v}`);
}