简体   繁体   English

在循环ES6的for中可迭代的函数调用

[英]Function call as iterable in for of loop ES6

Looking for best practice advice. 寻找最佳实践建议。

Is it a good practice to have function call in for of as iterable object? 它是一个很好的做法,在函数调用是迭代的对象?

const obj = {key1:'a', key2:'b'};

for(const i of Object.keys(obj)){ ... }

or better to have 或更好地拥有

const obj = {key1:'a', key2:'b'};
const allKeys = Object.keys(obj);
for(const i of allKeys){ ... }

Isn't Object.keys function called on every iteration of the loop? 循环的每次迭代都不会调用Object.keys函数吗?

you can check it by mocking a similar case 您可以通过模拟类似情况来检查它

 function A(){ console.log('function called'); return [1, 2, 3, 4, 5]; } for(let i of A()){ console.log(i); } 

As you can see A() is called only once 如您所见,A()仅被调用一次

Your first example does the same thing as the second, just without the allKeys constant. 您的第一个示例与第二个示例具有相同的功能,只是没有allKeys常量。 In your first example: 在第一个示例中:

const obj = {key1:'a', key2:'b'};

for(const i of Object.keys(obj)){ ... 

... Object.keys will only get called once , and then its iterator will be retrieved and used for the loop. ... Object.keys仅被调用一次 ,然后它将检索其迭代器并将其用于循环。 (This is covered in ForIn/OfHeadEvaluation in the spec, but it's...heavy going.) So you're fine using that form, it's not inefficient. (这在规范的ForIn / OfHeadEvaluation中进行了介绍,但是它... 工作量很大。)因此,使用该表格可以很好地解决问题,它的效率并不低。

The call to Object.keys is only made once in both variants. 在这两个变体中,仅对Object.keys进行一次调用。

But consider also as possibility this for loop that does not depend on Object.keys : 但也可以考虑以下不依赖于Object.keys for循环:

for (const prop in obj) {  } 

Object.keys creates an array, while the above for loop does not. Object.keys创建一个数组,而上面的for循环则没有。 The latter only retrieves the items as necessary. 后者仅在必要时检索项目。 Of course, if your for loop is never exited prematurely, it will still retrieve all of them, so this only makes a difference when you plan to exit the loop prematurely. 当然,如果您的for循环永远不会过早退出,它仍然会检索所有循环,因此这仅在您计划过早退出循环时有所不同。 In that case the corresponding iterator never visits the remaining items, while Object.keys would already have done so in creating the array. 在这种情况下,相应的迭代器将永远不会访问其余项,而Object.keys在创建数组时就已经这样做了。

One thing to pay attention to: a for .. in loop will also iterate enumerable inherited properties, not only own properties, while Object.keys will only list own enumerable properties. 要注意的一件事: for .. in循环还将迭代可枚举的继承属性,不仅是自己的属性,而Object.keys仅列出自己的可枚举属性。 You can add an extra test in the for loop to exclude non-own properties: 您可以在for循环中添加一个额外的测试,以排除非自有属性:

if (obj.hasOwnProperty(prop))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM