zoukankan      html  css  js  c++  java
  • 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#

  • 相关阅读:
    Android自动化测试解决方案
    Oracle数据库的DML命令的处理过程详解
    Oracle数据库的BULK COLLECT用法之批量增删改
    建设DevOps能力,实现业务敏捷
    强大的C# Expression在一个函数求导问题中的简单运用
    Visual Studio 11开发者预览版发布(附下载)
    js table隔行变色
    编译原理语法推导树
    巧用数据库归档技术解决性能下降问题
    编译原理正规式和有限自动机
  • 原文地址:https://www.cnblogs.com/eret9616/p/12006390.html
Copyright © 2011-2022 走看看