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

时间:2022-03-06 04:31:53

This question already has an answer here:

这个问题在这里已有答案:

jerry = {
  weight: 178

}

Malcom = {
  weight: 220
}

Bob = {
  Weight: 134

}

people = [jerry, Malcom, Bob]

console.log(people[0]);

I'm trying to get a console.log of the object's name, "jerry". thanks for any and all help!

我正在尝试获取对象名称“jerry”的console.log。感谢任何和所有的帮助!

2 个解决方案

#1


3  

You can't. Jerry,Malcom, and Bob are just the variable names, you have two obvious solutions:

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

Add a name attribute to your objects.

为对象添加名称属性。

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

Or change your array to an object, and use the key as the name of your object.

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

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

For example:

例如:

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);
  }
}

#2


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

#1


3  

You can't. Jerry,Malcom, and Bob are just the variable names, you have two obvious solutions:

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

Add a name attribute to your objects.

为对象添加名称属性。

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

Or change your array to an object, and use the key as the name of your object.

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

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

For example:

例如:

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);
  }
}

#2


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