for-in循环VS in-operator [英] for-in loop VS in-operator

查看:172
本文介绍了for-in循环VS in-operator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为自己是JS老手,但是刚刚第一次意识到在循环中的 in 运算符:

  (true)
for(k in []){if(k ==length)alert(); }; // k永远不会是长度

所以这引出了我的问题:为什么是 for ... in 循环中运算符中的

Imho这是完全误导,因为它做不同的事情。此外,首先操作的使得JS引擎获取所有可枚举的属性,然后在该子集上操作符中的使用的是imho错误:仅仅是因为操作符中的接受了所有可能的属性,无论是原型还是自己的属性,无论是访问器属性还是数据属性。那么如果已经减少到可枚举对象的属性,那么如何过滤掉所有的东西呢?

div>


所以这给我带来了我的问题:为什么运算符中的都存在于中... 循环?


不是。 for ... in 循环结构中的标记中的标记不是一个运算符,它同样不是一个运算符表达

  x = {in:5} .in 

这只是其中一个令牌,可以区分 www.ecma-international.org/ecma-262/6.0/#sec-for-statementrel =nofollow> for(...; ...; ...) 循环。鉴于(...)语句不存在,在标记中的 http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statementsrel =nofollow>关系表达式永远不会与此冲突。

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?

解决方案

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.

这篇关于for-in循环VS in-operator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆