2012-04-04 17 views
0

我有一个图像数组,其中有多个图像。不是固定的,可以是一个或两个或8时,我有定影图像的编号,然后我使用的代码是这样的需要关于构建逻辑,向对象添加属性的帮助

var details = { 

    image1: { 
     position: 0, 
     title: $slideDiv.children().eq(0).attr("alt") 
    }, 
    image2: { 
     position: -400, 
     title: $slideDiv.children().eq(1).attr("alt") 
    }, 
    image3: { 
     position: -800, 
     title: $slideDiv.children().eq(2).attr("alt") 
    }, 
    image4: { 
     position: -1200, 
     title: $slideDiv.children().eq(3).attr("alt") 
    }, 
    image5: { 
     position: -1600, 
     title: $slideDiv.children().eq(4).attr("alt") 
    } 

}; //end of var details 

但现在我有在阵列的图像。我希望细节对象添加的图像等于数组中的图像数量。我想是这样的

var details = {}; 
var position = 0; 
images.each(function(index){ 
    details.("image" + index) : { 
     position: position, 
     title: $slideDiv.children().eq(index).attr("alt") 
    } 

    position += -400; 

}) ; //end of .each() 

,我想提出的,如果我有图像阵列中的两个图像的就应该成为这样的事情

var details = { 
    image1: { 
     position: 0, 
     title: $slideDiv.children().eq(1).attr("alt") 
    }, 
    image2: { 
     position: -400, 
     title: $slideDiv.children().eq(2).attr("alt") 
    } 

} 

的逻辑,但是这是行不通的。当然我的语法错了

details.("image" + index) : {..} 

我该怎么做?

感谢

+0

为什么不只是让一个数组,而不是命名属性的对象? – 2012-04-04 05:21:59

+0

我正在建设图片库。当图像的数量是固定的,然后逻辑与对象。所以现在我只是想把事情变成动态的而不是静态的。所以我使用相同的逻辑,但现在所有的变量都相对于阵列中的图像数量进行设置 – Basit 2012-04-04 05:28:17

+0

为了清晰起见,您可能需要切换到数组。通常,只有在您无法预先预测名称的情况下,才会执行'obj [name]'语法。这里的名称遵循这样的规则模式,它们实际上并没有告诉你任何有关特定元素的信息,并且使得单个元素的存储和检索变得复杂。 – 2012-04-04 05:40:01

回答

0

正确的语法是:details['image' + index]可以在以后通过details.image0访问,details.image1

所以它应该是:details['image' + index] = {prop: val}

+0

Woops,为时已晚。 – powerbuoy 2012-04-04 05:04:28

+0

它也无法正常工作'details ['image'+ index]:{ position:position, title:$ slideDiv.children()。eq(index).attr(“alt”) }错误是* *失踪 ;之前的语句**在线'detail ['image'+ index]:{' – Basit 2012-04-04 05:07:44

+0

它需要:'details ['image'+ index] = {prop:val}' – powerbuoy 2012-04-04 05:09:06

1

在Javascript中,你可以访问属性的方式有两种:

obj.property 

相当于

obj["property"] 

所以你的情况,你会希望把它写像此:

details["image"+index]