This question already has an answer here:
这个问题在这里已有答案:
- Get name of object or class 6 answers
- 获取对象或类6答案的名称
- How to convert variable name to string in JavaScript? 3 answers
- 如何在JavaScript中将变量名转换为字符串? 3个答案
- Variable name as a string in Javascript 11 answers
- 变量名称作为Javascript 11答案中的字符串
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 )