在js中,

对于Object,一般for...in 来进行迭代,不能使用for...of     // let obj = {a:1,b:2} for(let i of obj){console.log(i)} // err

对于Array,一般使用for...of来迭代 (不建议使用for..in来迭代)

原因:

The difference between iterable (e.g. arrays) and non-iterable (native object) collections is that the iterable ones have a solid definition on the order by which their elements should be iterated. Objects are just lookups, and the spec states that you should never rely on the order of keys or values (e.g. when using a for-in loop), hence why they are not considered "iterable".

Object不能调用for...of,虽然Object可以调用for...in,但是顺序是不能被保证的,不同引擎的实现可能不同。因为Object中的字段只是lookup(指针查找),不像js中数组对象有定义好的顺序(0,1,2...),所以他们设计初并不是"iterable"的。于是不能使用for...of,但是可以用for...in来打印出来(for...in的顺序依据浏览器引擎实现不同,而不同。)

对于Array,不建议进行for...in操作是因为,数组的index的顺序一般是引擎内建实现的,如果你手动操作他容易产生不可预料结果,所以不建议(虽然可以,这里和Object有点不同,Object的for...of是直接打不出来)

*额外内容:

1.为了实现对象的for...of,可以通过实现Symbol.iterator接口

这里有一个例子:

2. 对于Object直接获取值,可以通过Object.keys(),for...in,或者Object.entries()

资料:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

https://stackoverflow.com/questions/29885220/using-objects-in-for-of-loops#

随机推荐

  1. 【TCP】拥塞控制

    TCP拥塞控制 出现拥塞           ∑对资源的需求 > ∑可用资源 拥塞控制是防止过多的数据注入到网络中,使网络中的路由器或链路不过载,这是一个全局性的. 流量控制是点对点的通信量的控 ...

  2. Ubuntu 18.04 安装配置 MySQL 5.7

    Ubuntu 18.04 安装 mysql 的过程中,竟然没有让你输入秘密?!(之前在 Ubuntu 14.04 下,安装过程中会询问密码),这导致安装完 mysql 初始秘密不知道的问题. $ su ...

  3. mongo批量插入问题(insert_many,bulk_write),spark df转json传入mongo

    https://blog.csdn.net/nihaoxiaocui/article/details/95060906 https://xuexiyuan.cn/article/detail/173. ...

  4. C#工具:ASP.net 调用MySQL 帮助类(包括存储过程调用)

    1.创建DbHelperMySQL类 2.复制代码到类中 using System; using System.Collections; using System.Collections.Specia ...

  5. JS 数组相关的操作函数

    // 1.数组拼接 concat() var a = [1, 2]; var b = [3, 4]; console.log(a.concat(b)); // [1, 2, 3, 4] // 2.数组 ...

  6. Pandas中DataFrame数据合并、连接(concat、merge、join)之join

    pandas.DataFrame.join 自己弄了很久,一看官网.感觉自己宛如智障.不要脸了,直接抄 DataFrame.join(other, on=None, how='left', lsuff ...

  7. 把task加入websocket服务端程序

    服务端代码 <?php //task任务要实现两个方法onfinish ontask //还要设置worker_num date_default_timezone_set("PRC&q ...

  8. 自制centos6开机界面

    1.先准备好一张640x480大小的图片并上传至主机(可在画图工具中调整图片大小) 注意如没有rz命令,可以先安装: yum install lrzsz 2.制作背景图 制作需要用到convert命令 ...

  9. “我”这个字的unicode码到底是25105

    “我”这个字的unicode码到底是25105 “我”这个字的unicode码到底是25105 “我”这个字的unicode码到底是25105

  10. 3 监控项、触发器、web监控、nginx监控

    1.自定义监控项 Item 参数文档 https://www.zabbix.com/documentation/3.0/manual/config/items/itemtypes/zabbix_age ...