回头再来补充
TODO:
The confusion between for...in and for...of arises from their different purposes and behaviors in JavaScript.
-
for...in: This loop iterates over the enumerable property names (keys) of an object. In your example with the array:
var arr = [3, 5, 7]; arr.foo = "hello"; for (var i in arr) { console.log(i); // logs "0", "1", "2", "foo" }Here,
for...ingoes through all the keys of the array, including the custom propertyfoo, because JavaScript arrays are actually objects andfoois an enumerable property of that object. -
for...of: This loop is designed to iterate over iterable objects (like arrays, strings, maps, etc.) and it retrieves the values, not the keys. It does not go through properties that are not part of the iterable structure:
for (var i of arr) { console.log(i); // logs "3", "5", "7" }In this case, it only logs
3,5, and7becausefor...ofis intentionally designed to iterate over the values of the iterable object (the array in this case). The added propertyfoois not considered part of the array's values and will not be logged.
So, to summarize, for...in accesses keys of properties while for...of accesses the values of iterable objects. This distinction is intentional in JavaScript to provide different ways to iterate through data structures based on your needs.