对象是没有迭代器的,所以对于伪数组有迭代器需求的情况我可以手动在Object原型上定义一个迭代器,用于迭代伪数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| let fakeArr = { 0: 'a', 1: 'b', 2: 'c', 99: 'zzz', length: 3,
}
Object.prototype[Symbol.iterator] = function* () {
let keys = Object.keys(this); let regExpNum = new RegExp(/[0-9]+/) for (let key of keys) { if (regExpNum.test(key)) yield this[key] } }
for (let item of fakeArr) { console.log(item); }
|