for...in 与 for...of
在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#
随机推荐
- ProgressDialog 进度条的初步认识
public class MainActivity extends Activity implements View.OnClickListener{ private ProgressBar prog ...
- 使用TextView和Textedit
1.TextView res/layout 中设置布局文件 hint属性:提示输入信息text属性:与hint的区别---hint仅仅是提示:text是实际的内容讲布局xml文件引入到activit ...
- java开发技巧
1,IDEA辅助功能Shift +F2去到有错误的地方Alt+Enter,会给出解决错误的建议: 2,调试,没问题的步骤,直接跳过,不要跳入细节: 调试时,要明确要跟踪的变量,不要陷入混乱: 3,调试 ...
- cubase 使用冻结功能 节省电脑资源
- HDU - 4992 Primitive Roots (原根)
模板题,可用于求一个数的所有原根. #include<bits/stdc++.h> using namespace std; typedef long long ll; ,inf=0x3f ...
- 重温JSP学习笔记
<% double d1 = 3.5; double d2 = 4.4; pageContext.setAttribute("d1", d1); pageContext.se ...
- stm32之HAL串口中断的callback流程图
- Ubuntu16.04连接SSH出现 Server responded “Algorithm negotiation failed” 的解决方法
今天安装了Ubuntu16.04虚拟机,与SSH连接时出现了如下问题 解决方法如下: (写在前面:请先确保自己已经给Ubuntu安装了SSH服务.安装方法是在root模式下,终端输入命令apt-g ...
- mongodb多条件分页查询的三种方法(转)
一.使用limit和skip进行分页查询 public List<User> pageList(int pageNum ,int pageSize){ List<User> u ...
- [Javascirpt] What’s new in JavaScript (Google I/O ’19)
Private variable in class: class Counter { #count = 0; // cannot be access publicly get value () { r ...