0

I want to get the values of an array that looks like this:

t = new Object();
t.erg = new Array();
t.erg['random1'] = "something1";
t.erg['random2'] = "something2";
t.erg['random3'] = "something3";
t.erg['random4'] = "something4";

But i want to get the random names and then the values of them through a loop, I can't find a way to do it :/

eruducer
  • 31
  • 6
  • possible duplicate of [How to list the properties of a javascript object](http://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object). NB, [you're using `Array` incorrectly](http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/). – Andy E Dec 09 '11 at 23:29

3 Answers3

2

You would use the other form of the for loop:

for (x in t.erg) {
  if (t.erg.hasOwnProperty(x)) {
    alert("key is " + x + " value is " + t.erg[x]);
  }
}
Peter Smith
  • 849
  • 2
  • 11
  • 28
0

To get a random value, you could get a random number and append it to the end of the string "random".

Something like this might work:

 var randomVal = "random" + Math.floor(Math.random()*4);
Jeffrey Sweeney
  • 5,986
  • 5
  • 24
  • 32
0

To get the the names of something you would use a for in loop, but you are actually creating to objects not an object and an array. Why not use literals like this

t={
  erg:{
    'random1':'something1',
    'random2':'something2'
  }
}

for(var x in t.erg){
  //in the first round of the loop
  //x holds random1
}
qw3n
  • 6,236
  • 6
  • 33
  • 62