1. 不用管数组内部有添加了几个对象,都遍历出来
const todos = {
life: ['吃饭', '睡觉', '打豆豆'],
learn: ['语文', '数学', '外语'],
work: ['喝茶'],
each: function (callback) { // 提供统一遍历访问接口
const all = [].concat(this.life, this.learn, this.work)
for (const item of all) { callback(item)
} ,
// 提供迭代器(ES2015 统一遍历访问接口)
[Symbol.iterator]: function () {
const all = [...this.life, ...this.learn, ...this.work]
let index = 0
return {
next: function () {
return {
value: all[index],
done: index++ >= all.length
}
}
}
}
},
todos.each(function (item) { console.log(item) })
console.log('-------------------------------')
for (const item of todos) { console.log(item) }