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是直接打不出来)

扫描二维码关注公众号,回复: 8116384 查看本文章

*额外内容:

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#

猜你喜欢

转载自www.cnblogs.com/eret9616/p/12006390.html