在 javascript 中,我有一个对象数组。我如何控制台记录对象的名称,而不是内容?

In javascript, I have an array of objects. How do I console log the name of the object, rather than the contents?

jerry = {
  weight: 178

}

Malcom = {
  weight: 220
}

Bob = {
  Weight: 134

}

people = [jerry, Malcom, Bob]

console.log(people[0]);

我正在尝试获取对象名称 "jerry" 的 console.log。感谢您提供的所有帮助!

ES6 版本: 使用 Object#entries, Array#forEach, and destructuring

const jerry = {weight: 178}
const Malcom = {weight: 178}
const Bob = {weight: 178}

const people = {jerry, Malcom, Bob}

const res = Object.entries(people).forEach(([name, {weight}])=>{
  console.log(name, weight);
});


你不能。 Jerry、Malcom 和 Bob 只是变量名,您有两个明显的解决方案:

为您的对象添加 name 属性。

var jerry = {
 name: "jerry",
 weight: 178
}

或者将数组更改为对象,并使用键作为对象的名称。

var people = {jerry: jerry, malcom: Malcom, bob: Bob}

例如:

var jerry = {
  weight: 178
}

var Malcom = {
  weight: 178
}

var Bob = {
  weight: 178
}

var people = {jerry: jerry, malcom: Malcom, bob: Bob}

for(var person in people){
  if(people.hasOwnProperty(person)){
    console.log(person, people[person].weight);
  }
}

var Some = {
  MyValue : 1234
}
for (var i in Some) console.log(i);

var people = {
 jerry : { weight: 178 },
 Malcom : { weight: 220 },
 Bob : { weight: 134 }
}

for (var i in people) console.log( i +' : '+ people[i].weight )