如何在 grandCouncil 数组中获取正确的对象变量名称?
How do I get the correct object variable names in the grandCouncil array?
当我 console.log(grandCouncil) 我最终得到这个:
[Object, Object, Object]
我想看到的是变量的名称而不是像这样:
[jungleAnimal1, jungleAnimal2, jungleAnimal3]
这是我的代码:
var grandCouncil = [];
var jungleAnimal1 = {
'type': "frog",
'collects': ['flys','moths','beetles'],
'canFly': false
};
var jungleAnimal2 = {
'type': "jaguar",
'collects': ['wild pigs','deer','sloths'],
'canFly': false
};
var jungleAnimal3 = {
'type': "parrot",
'collects': ['fruits','bugs','seeds'],
'canFly': true
};
grandCouncil.push(jungleAnimal1,jungleAnimal2,jungleAnimal3);
console.log(grandCouncil);
jungleAnimal1、2 和 3 是对象文字。
当您将它们推入 grandCouncil 数组时,对这些对象的引用会添加到数组中,但变量名不会。
如果你想使用jungleAnimal1,2和3作为grandCouncil下的properties,grandCouncil应该是一个对象,animals可以是属性,像这样:
grandCouncil = {
"jungleAnimal1" : { // type, collects, canFly }
"jungleAnimal2" : ...
"jungleAnimal3" : ...
}
感谢@zerkms 的澄清
数组中存储的值是对象;例如,您可以使用点表示法访问对象的值,因此要访问 jungleAnimal2 的类型只需:
grandCouncil[1].type
你可以
for(var i = 0;i < grandCouncil.length; i++){
for(animal in grandCouncil[i]){
console.log(animal);
}
}
这只是遍历每个数组元素,它是一个对象,然后遍历这些对象中的每个元素。您可以使用上述点表示法访问特定属性,因此对于 console.log 所有类型,只需执行 animal.type
.
当我 console.log(grandCouncil) 我最终得到这个:
[Object, Object, Object]
我想看到的是变量的名称而不是像这样:
[jungleAnimal1, jungleAnimal2, jungleAnimal3]
这是我的代码:
var grandCouncil = [];
var jungleAnimal1 = {
'type': "frog",
'collects': ['flys','moths','beetles'],
'canFly': false
};
var jungleAnimal2 = {
'type': "jaguar",
'collects': ['wild pigs','deer','sloths'],
'canFly': false
};
var jungleAnimal3 = {
'type': "parrot",
'collects': ['fruits','bugs','seeds'],
'canFly': true
};
grandCouncil.push(jungleAnimal1,jungleAnimal2,jungleAnimal3);
console.log(grandCouncil);
jungleAnimal1、2 和 3 是对象文字。
当您将它们推入 grandCouncil 数组时,对这些对象的引用会添加到数组中,但变量名不会。
如果你想使用jungleAnimal1,2和3作为grandCouncil下的properties,grandCouncil应该是一个对象,animals可以是属性,像这样:
grandCouncil = {
"jungleAnimal1" : { // type, collects, canFly }
"jungleAnimal2" : ...
"jungleAnimal3" : ...
}
感谢@zerkms 的澄清
数组中存储的值是对象;例如,您可以使用点表示法访问对象的值,因此要访问 jungleAnimal2 的类型只需:
grandCouncil[1].type
你可以
for(var i = 0;i < grandCouncil.length; i++){
for(animal in grandCouncil[i]){
console.log(animal);
}
}
这只是遍历每个数组元素,它是一个对象,然后遍历这些对象中的每个元素。您可以使用上述点表示法访问特定属性,因此对于 console.log 所有类型,只需执行 animal.type
.