我知道什么是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 Loop和for…的循环。

索引的对象

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

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

其他回答

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

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

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

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

/* Result:

3
5
7
hello

*/

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循环遍历对象的可枚举属性名。

for of (ES6新增功能)使用特定于对象的迭代器并遍历由该迭代器生成的值。

在你的例子中,数组迭代器产生数组中的所有值(忽略非索引属性)。

简单来说,forIN遍历数组(索引)/对象(键)中的key, 而forOF则遍历数组(value)的值。

//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