Reputation: 11
I got this array:
backgrounds:
{
bc2: '/images/layout/images/backgrounds/bc2.jpg',
codmw2: '/images/layout/images/backgrounds/codmw2_6.jpg',
bf2: '/images/layout/images/backgrounds/bf2.jpg',
bf2142: '/images/layout/images/backgrounds/bf2142.jpg',
codbo: '/images/layout/images/backgrounds/codbo.jpg',
cod5waw: '/images/layout/images/backgrounds/cod5waw.jpg'
}
and I want to access this like backgrounds[0] = '/images/layout/images/backgrounds/bc2.jpg'
.
Is this possible or do I need to create the array in another way?
Upvotes: 0
Views: 144
Reputation:
I just tried this in jsfiddle and it worked
var backgrounds = {
bc2: '/images/layout/images/backgrounds/bc2.jpg',
codmw2: '/images/layout/images/backgrounds/codmw2_6.jpg',
bf2: '/images/layout/images/backgrounds/bf2.jpg',
bf2142: '/images/layout/images/backgrounds/bf2142.jpg',
codbo: '/images/layout/images/backgrounds/codbo.jpg',
cod5waw: '/images/layout/images/backgrounds/cod5waw.jpg',
0: '/images/layout/images/backgrounds/bc2.jpg',
1: '/images/layout/images/backgrounds/codmw2_6.jpg',
2: '/images/layout/images/backgrounds/bf2.jpg',
3: '/images/layout/images/backgrounds/bf2142.jpg',
4: '/images/layout/images/backgrounds/codbo.jpg',
5: '/images/layout/images/backgrounds/cod5waw.jpg'
};
alert(backgrounds[0]);
So you could automate this with a loop to avoid duplication errors
var i = 0;
for(var prop in backgrounds) {
if(prop.search(/^\d+$/) == -1) { //avoid the infinite loop
backgrounds[i] = backgrounds[prop];
i++;
}
}
of course this means you have duplication of data
Upvotes: 0
Reputation: 31883
In this case, backgrounds is an object, i.e., an associative array. You can't use numerical indexes now to access its members. You can iterate through it using for( var prop in backgrounds)
or you can address its members directly (backgrounds.bc2 or backgrounds['bc2']
).
Upvotes: 2
Reputation: 9440
I should do it like this:
var backgrounds =
{
bc2: '/images/layout/images/backgrounds/bc2.jpg',
codmw2: '/images/layout/images/backgrounds/codmw2_6.jpg',
bf2: '/images/layout/images/backgrounds/bf2.jpg',
bf2142: '/images/layout/images/backgrounds/bf2142.jpg',
codbo: '/images/layout/images/backgrounds/codbo.jpg',
cod5waw: '/images/layout/images/backgrounds/cod5waw.jpg'
};
backgrounds.bc2 = "test";
console.log(backgrounds.bc2) //test
Upvotes: 0