2014-01-19 152 views
1

目前我有一个填充数组的问题,我在代码中调用了input,我的代码中调用了athlete。使用其他几个数组实例化了名为athlete的对象。我附加了一个jsfiddle链接到这个帖子,这个帖子基本上是一个简化版本,具有相同的问题。我知道逻辑可能看起来多余,但是这是因为这个例子是必要的(实际的逻辑将与用户输入一起工作)。用Javascript中的对象填充数组

我的问题是我正在用new Athlete对象填充数组,但我无法访问数组中对象的特定属性。

我是新来处理对象,所以我会很感激任何关于如何使这项工作的建议。我添加了最后一行代码来显示我的输入数组。

var input = new Array(); 
var girl=[1,1,1,1]; 
var boy = [1,1,1,1]; 
var balleyscore = [100,400,320,50]; 
var boyHeight = [72,68,65,75]; 
var girlHeight=[60,57,65,55]; 
var boyAge = [19,32,22,25]; 
var girlAge = [20,15,32,18]; 
//the above are all generate from user inputs 
// they go into the object constructor below 
function athlete(girl, boy,balleyscore, height, age){ 
this.girl=girl; 
this.boy=boy; 
this.balleyscore=balleyscore; 
this.height=height; 
this.age = age; 
}; 
function insertToObjectArray() 
{ 
    var j=0;     
    var i=0; //insert all our data into one array of the load object 
    for(j = 0; j < girl.length;j++) 
    { 
     input[j]= new athlete(true,false,balleyscore[j],girlHeight[j],girlAge[j]); 
    } 
    for(j = girl.length; j <=girl.length+boy.length;j++) 
    { 
     input[j]= new athlete(false,true,0,boyHeight[i],boyAge[i]); 
     i++; 
    } 
}; 
insertToObjectArray(); 

document.getElementById("demo").innerHTML=input; 

http://jsfiddle.net/qC5j4/1/

+0

'我无法访问在array.'对象的特定属性是不够的调试程序。 :( – thefourtheye

+0

你试图访问哪个属性?究竟什么不能按照你的预期工作? –

+0

我需要能够访问每个属性 – bala

回答

1

要访问您的阵列输入一个对象的属性:

input[0].age 

这将允许您访问的第一位运动员的年龄

也可以这样访问:

input[0]['age'] 

无论哪种方式,他们都会显示20作为阵列中第一个运动员的年龄。

在调试器中通过console.log(输入)检出它,然后可以使用数据结构进行播放。

例:

document.getElementById("demo").innerHTML=input[0].age; 
1

不能确定你的问题,在这里我已经更新了你的提琴,通过将行

output[j]= input[j].height 

fiddle

+0

为什么我不能使用输入[j] .height显示高度? – bala

+0

我需要能够稍后访问这些属性进行计算,将这些属性重新放回到另一个数组中会破坏创建对象的目的。 – bala

+0

你可以做到这一点,在你的小提琴中你有一个对象的数组,你写到屏幕上,所以你有'对象'显示,我只是改变输出到屏幕上的Object.property,以便该属性显示 – RoyTheBoy

1

您展现运动员的高度财产可以通过数组索引和属性名称访问您的对象。此行document.getElementById("demo").innerHTML=input更改此代码(列表中的所有对象的性别和balleyscore在UL#演示):

for (var i=0; i<input.length; i++) { 
    var node = document.createElement('li'), 
     txt = document.createTextNode(
      (input[i].girl? 'girl' : 'boy') + ' ' + input[i].balleyscore); 
    node.appendChild(txt); 
    document.getElementById("demo").appendChild(node); 
} 

HTML:

<p><ul id="demo"></ul></p> 

FIDDLE

浏览器控制台是用于调试目的非常有用的。尝试在控制台对象创建后,加入这行和检查数组:

insertToObjectArray(); 
console.log(input);  // output input array to console 
1

你的运动员对象应该是例如:

function athlete(age) 
{ 
    this.age = age; 
} 

var item = new athlete(10); 
item.age;//10 
1

您可以显示这样的身高和年龄:

var output = ""; 
for(var i = 0, length = input.length; i !== length; i++) { 
    output += "height: "+input[i].height + ", age: " + input[i].age + "<br />"; 
} 
document.getElementById("demo").innerHTML=output; 

还有一个小错误。使用

j < girl.length+boy.length 

,而不是

j <=girl.length+boy.length 
+0

无论如何,这是一个危险的构造。而是用于(i = 0; i miraculixx