for-in loop VS in-operator

一曲冷凌霜 提交于 2019-12-02 07:21:48

问题


I consider myself a JS veteran but just now for the first time I have realised that the for ... in loop does something very different from the in operator:

"length" in []; // true
for (k in []) { if(k == "length") alert(); }; // k will never be "length"

So this brings me to my question: why is the in operator at all present in the for ... in loop?

Imho it is totally misleading, as it does different things. Also the notion that first the for operation makes the JS engine take all enumerable properties and then on that subset the in operator is used is imho wrong: simply because the in operator accepts all possible properties whether prototype or own, whether accessor- or data-properties. So how does it filter anything out if for has already reduced to enumerable object properties?


回答1:


So this brings me to my question: why is the in operator at all present in the for ... in loop?

It isn't. The in token in the for … in loop construct is not an operator, just as much it is not one in the expression

x = {in: 5}.in

It's just one of the tokens that distinguishes a for ( … in … ) from a for (…; …; …) loop. Given that there is no for (…) statement, the role of the in token in a relational expression never collides with this.



来源:https://stackoverflow.com/questions/33454474/for-in-loop-vs-in-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!