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#

  • 相关阅读:
    Hystrix使用说明,配置参数说明
    服务限流 -- 自定义注解基于RateLimiter实现接口限流
    Java生产环境下问题排查
    Java垃圾回收(GC)机制详解
    RabbitMQ如何解决各种情况下丢数据的问题
    JWT如何在Spring Cloud微服务系统中在服务相互调时传递
    LeetCode 117th Weekly Contest 总结
    系统设计总结
    单调栈总结
    LeetCode 116th Weekly Contest 总结
  • 原文地址:https://www.cnblogs.com/eret9616/p/12006390.html
Copyright © 2011-2022 走看看