jerry = {
weight: 178
}
Malcom = {
weight: 220
}
Bob = {
Weight: 134
}
people = [jerry, Malcom, Bob]
console.log(people[0]);
我正在尝试获取对象名称的console.log,“jerry”。感谢您的帮助!
答案 0 :(得分:3)
ES6版本:使用Object#entries,Array#forEach和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);
}
}
答案 1 :(得分:-3)
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 )