在 For Of 循环中使用对象 [英] Using Objects in For Of Loops
本文介绍了在 For Of 循环中使用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么不能在 for of 循环中使用对象?或者这是浏览器的错误?这段代码在 Chrome 42 中不起作用,说 undefined 不是函数:
Why isn't is possible to use objects in for of loops? Or is this a browser bug? This code doesn't work in Chrome 42, saying undefined is not a function:
test = { first: "one"}
for(var item of test) {
console.log(item)
}
推荐答案
我使用以下代码使对象可迭代:
I made objects iterable with this code:
Object.prototype[Symbol.iterator] = function*() {
for(let key of Object.keys(this)) {
yield([ key, this[key] ])
} }
用法:
for(let [ key, value ] of {}) { }
或者:
for(let [ key, value ] of Object.entries({})) { }
这篇关于在 For Of 循环中使用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文