【发布时间】:2014-11-20 16:27:39
【问题描述】:
我正在尝试遍历一个对象,将对象中的一些值放入一个新数组中。但是我很难弄清楚该怎么做。
这是我的对象:
var vehicles = {
list:{
"transport":{ //<-- This is the values I want to put to an array
name:"transport",
pixelWidth:31,
pixelHeight:30,
pixelOffsetX:15,
pixelOffsetY:15,
radius:15,
speed:15,
sight:3,
cost:400,
hitPoints:100,
turnSpeed:2,
spriteImages:[
{name:"stand",count:1,directions:8}
],
},
"harvester":{ //<-- This is the values I want to put to an array
name:"harvester",
pixelWidth:21,
pixelHeight:20,
pixelOffsetX:10,
pixelOffsetY:10,
radius:10,
speed:10,
sight:3,
cost:1600,
hitPoints:50,
turnSpeed:2,
spriteImages:[
{name:"stand",count:1,directions:8}
],
},
"scout-tank":{ //<-- This is the values I want to put to an array
name:"scout-tank",
canAttack:true,
canAttackLand:true,
canAttackAir:false,
weaponType:"bullet",
pixelWidth:21,
pixelHeight:21,
pixelOffsetX:10,
pixelOffsetY:10,
radius:11,
speed:20,
sight:3,
cost:500,
hitPoints:50,
turnSpeed:4,
spriteImages:[
{name:"stand",count:1,directions:8}
],
},
"heavy-tank":{ //<-- This is the values I want to put to an array
name:"heavy-tank",
canAttack:true,
canAttackLand:true,
canAttackAir:false,
weaponType:"cannon-ball",
pixelWidth:30,
pixelHeight:30,
pixelOffsetX:15,
pixelOffsetY:15,
radius:13,
speed:15,
sight:4,
cost:1200,
hitPoints:50,
turnSpeed:4,
spriteImages:[
{name:"stand",count:1,directions:8}
],
}
}
阅读其他帖子,我觉得我应该使用 for-in 循环。对我来说真正的挑战是从我的对象中获得正确的价值。我已经查看了这个post 来尝试解决它。
我找到了一个类似这样的解决方案:
var arr = [];
for (var key in vehicles)
{
var obj = vehicle[key];
for (var prop in obj)
{
if(obj.hasOwnProperty(prop))
{
arr.push(prop);
}
}
}
console.log(arr);
但我只是从控制台收到这条消息:
Array[0]length: 0__proto__: Array[0]
我还有一个正在运行的小提琴here
所有帮助将不胜感激。
【问题讨论】:
-
它有效,如果你修正错字:
vehicle->vehicles。
标签: javascript arrays object for-loop for-in-loop