for in forof
时间: 2023-08-26 10:17:49 浏览: 104
for..in与for..of迭代器
"for in" and "for of" are both used in JavaScript for looping over iterable objects, but they differ in how they iterate over the elements.
The "for in" loop is used to iterate over the keys of an object. It works by iterating over all enumerable properties of an object, including the properties inherited from its prototype chain. Here's an example:
```javascript
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key); // prints 'a', 'b', 'c'
}
```
On the other hand, the "for of" loop is used to iterate over the values of an iterable object. It works with arrays, strings, sets, maps, and other collection-like objects. Here's an example:
```javascript
const arr = [1, 2, 3];
for (const value of arr) {
console.log(value); // prints 1, 2, 3
}
```
Note that the "for of" loop does not work with regular objects because they are not iterable by default. However, you can use the "Object.entries()" method to convert an object into an iterable array and then use "for of" to iterate over its entries.
I hope this clarifies the difference between "for in" and "for of" loops in JavaScript! Let me know if you have any more questions.
阅读全文