答案:
for...of不能直接遍历对象,for in可以直接遍历对象
原因:
for...of需要实现iterator接口,对象没有实现iterator接口
解决:
const obj = {a: 1, b: 2}
for (let item of Object.keys(obj)) a b
for (let item of Object.values(obj)) 1 2
for (let item of Object.entries(obj)) ["a" 1] ["b" 2]
手动实现iterator:
obj[Symbol.iterator] = function() { let index = 0; console.log(this) const _this = this; let keys = Object.keys(_this); let length = keys.length; return { next () { if (index < length) { return { value: _this[keys[index++]], done: false } } else { return { value: null, done: true } } } } }
以上都可以实现for of遍历对象