在循环中使用对象 [英] Using Objects in For Of Loops

查看:134
本文介绍了在循环中使用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能使用对象进行循环?还是这个浏览器错误?该代码在Chrome 42中不起作用,说未定义不是一个功能:

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 {}) { }

这篇关于在循环中使用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆