Difference between ( for... in ) and ( for... of ) statements?

71 阅读1分钟

StackOverflow 原文

回头再来补充

TODO:

The confusion between for...in and for...of arises from their different purposes and behaviors in JavaScript.

  1. 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...in goes through all the keys of the array, including the custom property foo, because JavaScript arrays are actually objects and foo is an enumerable property of that object.

  2. 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, and 7 because for...of is intentionally designed to iterate over the values of the iterable object (the array in this case). The added property foo is 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.