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 :/
3 Answers 3
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]);
}
}
answered Dec 9, 2011 at 23:30
Peter Smith
8893 gold badges11 silver badges28 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Dec 9, 2011 at 23:31
Jeffrey Sweeney
6,1545 gold badges27 silver badges32 bronze badges
Comments
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
}
answered Dec 9, 2011 at 23:33
qw3n
6,3446 gold badges36 silver badges63 bronze badges
Comments
lang-js
Arrayincorrectly.