views:

67

answers:

4

Hi, I have a JS Object:

var testObj = new Object();

that has a property called volume1, so

testObj.volume1

has a value. How would I go about accessing that property by using something along the lines of

testObj.volume + "1"

To give it more context, the object actually has more properties, like

testObj.volume1, testObj.volume2 and testObj.volume3 

and I want to access them using some iteration. I've tried playing with the window[] element, but have had not much success.

Thanks!

+7  A: 
   testObj["volume" + 1]

but you actually want an array here

   testObj.volume = [...]
   testObj.volume[1] = whatever
stereofrog
Doh! I'm such an idiot!
Rio
A: 

Use something in the fashion of testObj["volume" + "1"] ;)

The notations object.property and object["property"] are (almost) equivalent in javascript.

Thomas Wanner
A: 

You can use for loop with in operation.

for(var PropName in testObj) {
    var PropValue = testObj[PropName];
    ....
}

In case, you only want the property with the name started with 'value' only, you can also do this:

for(var PropName in testObj) {
    if (!/^value[0-9]$/.match(PropName))
        continue;
    var PropValue = testObj[PropName];
    ....
}

OR if the number after the 'value' is always continuous you can just use a basic for loop.

for(var I = 0; I <= LastIndex; I++) {
    var PropName  = "value" + I;
    var PropValue = testObj[PropName];
    ....
}

Hope this helps.

NawaMan
+2  A: 

off topic it is considered better pratice to do

var testObj = {};

instead of

var testObj = new Object();
hojberg
+1 for the nice tip. However, this rather belongs to "comments" section, as it isn't an answer
stereofrog
sorry about that, am new to stackoverflow
hojberg