我知道什么是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”。为什么?

例子链接


当前回答

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

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

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

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

其他回答

For of用于遍历可迭代对象,For in用于遍历对象属性

这里有一个要记住的小技巧:

For of不是针对对象的(而是针对可迭代对象的)

For in不是针对可迭代对象的,而是针对对象的

另一个技巧:

For in返回对象索引(键),而For of返回值

我在迭代器和生成器中找到了完整的答案(虽然它适用于TypeScript,但也适用于JavaScript)

Both for..of and for..in statements iterate over lists; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated. Here is an example that demonstrates this distinction: let list = [4, 5, 6]; for (let i in list) { console.log(i); // "0", "1", "2", } for (let i of list) { console.log(i); // "4", "5", "6" } Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values. let pets = new Set(["Cat", "Dog", "Hamster"]); pets["species"] = "mammals"; for (let pet in pets) { console.log(pet); // "species" } for (let pet of pets) { console.log(pet); // "Cat", "Dog", "Hamster" }

每个人都解释了为什么会出现这个问题,但是仍然很容易忘记它,然后挠头为什么会得到错误的结果。尤其是当你处理大量数据时,乍一看结果似乎还不错。

使用对象。你确保去所有属性的条目:

var arr = [3, 5, 7];
arr.foo = "hello";

for ( var [key, val] of Object.entries( arr ) ) {
   console.log( val );
}

/* Result:

3
5
7
hello

*/

为…Of循环只对可迭代对象有效。在JavaScript中,可迭代对象是可以循环的对象。

String、Array、TypedArray、Map和Set都是内置的可迭代对象,因为它们的每个原型对象都实现了@@iterator方法。因此,对于…Of循环作用于上述的对象类型。

Object在JavaScript中默认是不可迭代的。因此,对于…Of循环对对象无效。

简单地说,对于……Of适用于字符串和数组,但不适用于对象。

为…In适用于那些可枚举标志设置为true的属性。

通过简单赋值或属性初始化器创建的属性的可枚举标志默认为true。 通过Object.defineProperty创建的属性的可枚举标志默认为false。

这里有一个更详细的例子:https://dev.to/swastikyadav/difference-between-forof-and-forin-loop-in-javascript-j2o

//for in,迭代对象中的键和数组中的索引

 let obj={a:1, b:2}
    
    for( const key in obj)
      console.log(obj[key]); //would print 1 and 2
      console.log(key);      //would print a and b

 let arr = [10, 11, 12, 13];

  for (const item in arr) 
    console.log(item);   //would print 0 1 2 3

//for of,迭代数组或任何可迭代对象中的值

let arr = [10, 11, 12, 13];

for (const item of arr )
  console.log(item);  //would print 10  11  12  13