java-script:for-in-vs-for-of
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
java-script:for-in-vs-for-of [2023/08/10 03:00] – odefta | java-script:for-in-vs-for-of [2023/08/11 12:22] (current) – odefta | ||
---|---|---|---|
Line 18: | Line 18: | ||
</ | </ | ||
- | ==== Example with an array ==== | + | ==== Example with an Array ==== |
<code javascript> | <code javascript> | ||
const arr = [10, 20, 30]; | const arr = [10, 20, 30]; | ||
Line 58: | Line 58: | ||
It can't be used directly on plain objects without using methods like Object.keys, | It can't be used directly on plain objects without using methods like Object.keys, | ||
</ | </ | ||
- | Example with an Array: | + | |
+ | ==== Example with an Array ==== | ||
<code javascript> | <code javascript> | ||
const arr = [10, 20, 30]; | const arr = [10, 20, 30]; | ||
Line 67: | Line 69: | ||
</ | </ | ||
- | ===== Example with an Object | + | ==== Example with an Object ==== |
The **for...of** loop is designed to work with iterable objects, such as arrays, strings, maps, sets, etc. Ordinary objects are not iterable by default, so **attempting to use for...of with an object will lead to an error.** | The **for...of** loop is designed to work with iterable objects, such as arrays, strings, maps, sets, etc. Ordinary objects are not iterable by default, so **attempting to use for...of with an object will lead to an error.** | ||
Line 73: | Line 75: | ||
However, you can convert an object' | However, you can convert an object' | ||
Example: | Example: | ||
- | < | + | < |
const person = { | const person = { | ||
name: ' | name: ' | ||
Line 109: | Line 111: | ||
In this example, **Object.keys(person)**, | In this example, **Object.keys(person)**, | ||
- | ====== Conclusion | + | ===== Conclusion ===== |
* Use **for...in** to iterate over the **keys** of an **object** (including non-array objects). | * Use **for...in** to iterate over the **keys** of an **object** (including non-array objects). |
java-script/for-in-vs-for-of.1691625650.txt.gz · Last modified: 2023/08/10 03:00 by odefta