为什么对象点符号在 for...in 循环中不起作用?

Why doesn't object dot notation work in a for...in loop?

car = { 
 color: 'green',
 speed: '340',
 drive: function() {
  alert("brrrrrrm");
 } 
}

这个有效:

for(elem in car) {
  console.log(car[elem]);
}

但这不起作用,returns 每个元素都未定义:

for(elem in car) {
  console.log(car.elem);
}

当你写 car.elem 时,你试图访问不存在的汽车对象 elem 属性。

但是当您使用 car[elem] 时,您正在尝试访问与存储在变量 elem 中的名称相同的汽车对象的 属性。

因此,如果您使用 "dot notation",您将最终调用汽车对象的元素 属性。

car = { 
 color: 'green',
 speed: '340',
 elem: 'This is the elem property of car object',
 drive: function() {
  alert("brrrrrrm");
 } 
}

访问属性:

for(elem in car) {
  console.log(car[elem]);
}

控制台输出:

green
340
This is the elem property of car object
function () {
  alert("brrrrrrm");
}

然后我们做:

for(elem in car) {
  console.log(car.elem);
}

控制台输出:

This is the elem property of car object
This is the elem property of car object
This is the elem property of car object
This is the elem property of car object