我知道什么是a。在循环中(它在键上迭代),但我听说for…的第一次(它遍历值)。

我对……感到困惑。的循环。

var arr = [3, 5, 7];
arr.foo = "hello";
    
for (var i in arr) {
  console.log(i); // logs "0", "1", "2", "foo"
}
    
for (var i of arr) {
  console.log(i); // logs "3", "5", "7"
  // it doesn't log "3", "5", "7", "hello"
}

我理解为……Of迭代属性值。那为什么它记录的不是"3" "5" "7" "hello"而是"3" "5" "7"

不像……循环中,遍历每个键("0","1","2","foo"),也遍历foo键,for…Of不会遍历foo属性的值,即“hello”。为什么会这样?

在此我为……的循环。它应该日志“3”,“5”,“7”,“你好”,但日志“3”,“5”,“7”。为什么?

例子链接


当前回答

有一些已经定义的数据类型,允许我们轻松地迭代它们,例如数组,映射,字符串对象

正常情况下,for in在迭代器上迭代,in response为我们提供了按插入顺序排列的键,如下例所示。

  const numbers = [1,2,3,4,5];
   for(let number in number) {
     console.log(number);
   }

   // result: 0, 1, 2, 3, 4

现在如果我们对for of进行同样的操作,那么作为响应,它提供给我们的是值而不是键。如

  const numbers = [1,2,3,4,5];
   for(let numbers of numbers) {
    console.log(number);
  }

  // result: 1, 2, 3, 4, 5

因此,观察这两个迭代器,我们可以很容易地区分它们之间的区别。

注意:- For of只适用于Symbol.iterator

因此,如果我们尝试在普通对象上迭代,那么它会给我们一个错误,例如-

const Room = {
   area: 1000,
   height: 7,
   floor: 2
 }

for(let prop in Room) {
 console.log(prop);
 } 

// Result area, height, floor

for(let prop of Room) {
  console.log(prop);
 } 

Room是不可迭代的

现在为了遍历,我们需要定义一个ES6 Symbol。迭代器如

  const Room= {
    area: 1000, height: 7, floor: 2,
   [Symbol.iterator]: function* (){
    yield this.area;
    yield this.height;
    yield this.floors;
  }
}


for(let prop of Room) {
  console.log(prop);
 } 

//Result 1000, 7, 2

这就是For in和For of的区别。希望能消除这种差异。

其他回答

这里有一个有用的助记符来记住for…in Loop和for…的循环。

索引的对象

为…in Loop =>迭代数组中的索引。

为…of Loop =>遍历对象的对象。

A看到了很多好的答案,但我决定把我的5美分只是为了有一个好的例子:

For in循环

遍历所有可枚举的道具

let nodes = document.documentElement.childNodes; 对于(var键在节点中){ Console.log (key); }

For循环

遍历所有可迭代值

let nodes = document.documentElement.childNodes; 对于(var节点中的节点){ console.log(node.toString()); }

当我第一次开始学习for in和of循环时,我也对我的输出感到困惑,但通过一些研究和理解,你可以像下面这样思考单个循环: 的

为…在循环中返回单个属性的索引,对属性的值没有影响,它循环并返回关于属性的信息,而不是关于属性的值。 如

Let profile = { 名字叫拿弗他利。 年龄:24岁 favCar:“野马”, 最喜欢的饮料:百利酒 }

上面的代码只是创建了一个名为profile的对象,我们将在两个示例中使用它,因此,当您在示例中看到profile对象时,不要感到困惑,只需知道它已被创建。

现在让我们用for…在下面的循环中

for(let myIndex in profile){
    console.log(`The index of my object property is ${myIndex}`)
}
 // Outputs : 
        The index of my object property is 0
        The index of my object property is 1
        The index of my object property is 2
        The index of my object property is 3

现在输出的原因是,我们的配置文件对象中有四(4)个属性,我们都知道索引从0开始…N,我们得到了属性的下标0,1,2,3因为我们使用的是for. in循环。

for...of loop* can return either the property, value or both, Let's take a look at how. In javaScript, we can't loop through objects normally as we would on arrays, so, there are a few elements we can use to access either of our choices from an object. Object.keys(object-name-goes-here) >>> Returns the keys or properties of an object. Object.values(object-name-goes-here) >>> Returns the values of an object. Object.entries(object-name-goes-here) >>> Returns both the keys and values of an object.


下面是它们的用法示例,请注意Object.entries():

Step One: Convert the object to get either its key, value, or both.
Step Two: loop through.


// Getting the keys/property

   Step One: let myKeys = ***Object.keys(profile)***
   Step Two: for(let keys of myKeys){
             console.log(`The key of my object property is ${keys}`)
           }

// Getting the values of the property

    Step One: let myValues = ***Object.values(profile)***
    Step Two : for(let values of myValues){
                 console.log(`The value of my object property is ${values}`)
               }

当使用object .entries()时,需要调用对象上的两个条目,即键和值。您可以通过条目中的任意一个调用两者。下面的例子。

Step One: Convert the object to entries, using ***Object.entries(object-name)***
Step Two: **Destructure** the ***entries object which carries the keys and values*** 
like so **[keys, values]**, by so doing, you have access to either or both content.


    // Getting the keys/property

       Step One: let myKeysEntry = ***Object.entries(profile)***
       Step Two: for(let [keys, values] of myKeysEntry){
                 console.log(`The key of my object property is ${keys}`)
               }

    // Getting the values of the property

        Step One: let myValuesEntry = ***Object.entries(profile)***
        Step Two : for(let [keys, values] of myValuesEntry){
                     console.log(`The value of my object property is ${values}`)
                   }

    // Getting both keys and values

        Step One: let myBothEntry = ***Object.entries(profile)***
        Step Two : for(let [keys, values] of myBothEntry){
                     console.log(`The keys of my object is ${keys} and its value 
is ${values}`)
                   }

对不清楚的部分提出意见。

for. in和for. of的区别:

for..in和for..of都是循环结构,用于遍历数据结构。它们之间唯一的区别是实体 它们迭代:

For ..in迭代对象的所有可枚举属性键 For ..of迭代可迭代对象的值。可迭代对象的例子有数组、字符串和nodelist。

例子:

Let arr = ['el1', 'el2', 'el3']; 加勒比海盗。adddedprop = 'arrProp'; // elKey是属性键 for(让elKey在arr中){ console.log (elKey); } // elValue是属性值 for (let elValue of arr) { console.log (elValue) }

在这个例子中,我们可以观察到for.. In循环遍历对象的键,在这个例子中,对象是数组对象。键是0,1,2(对应数组元素)和adddedprop。这是arr数组对象在chrome devtools中的外观:

你可以看到,我们的for..in循环只是简单地遍历这些键。


示例中的for..of循环遍历数据结构的值。这个例子中的值是'el1', 'el2', 'el3'。可迭代数据结构使用for..of返回的值取决于可迭代对象的类型。例如,数组将返回所有数组元素的值,而字符串则返回字符串中的每个字符。

这两个循环之间的另一个区别,之前没有人提到过:

解构……In已弃用。用于……相反。

因此,如果我们想在循环中使用解构,为了获取每个数组元素的索引和值,我们应该使用for…使用Array方法条目():

for (const [idx, el] of arr.entries()) {
    console.log( idx + ': ' + el );
}