我得到了这个数组:
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[0] = '/images/layout/images/backgrounds/bc2.jpg'
那样访问它。
这是可能的还是我需要以另一种方式创建数组?
答案 0 :(得分:2)
在这种情况下,背景是一个对象,即一个关联数组。您现在不能使用数字索引来访问其成员。您可以使用for( var prop in backgrounds)
进行迭代,也可以直接对其成员进行处理(backgrounds.bc2 or backgrounds['bc2']
)。
答案 1 :(得分:0)
我应该这样做:
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
答案 2 :(得分:0)
我刚刚在jsfiddle尝试过此功能
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]);
因此,您可以使用循环自动执行此操作以避免重复错误
var i = 0;
for(var prop in backgrounds) {
if(prop.search(/^\d+$/) == -1) { //avoid the infinite loop
backgrounds[i] = backgrounds[prop];
i++;
}
}
当然这意味着你有重复的数据