I have an images array in which there are number of images. Not fixed, may be one or two or 8. When i have fixed number of images then i was using the code something like this
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
But now i have images in array. I want that details object has added images in it equal to number of images in the array. I tried something like this
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()
The logic that i am trying to make is if i have two images in the images array the it should become something like this
var details = {
image1: {
position: 0,
title: $slideDiv.children().eq(1).attr("alt")
},
image2: {
position: -400,
title: $slideDiv.children().eq(2).attr("alt")
}
}
but this is not working. Of course my syntax is wrong
details.("image" + index) : {..}
How can i do this?
Thanks
obj[name]
syntax only in cases where you couldn't predict the name in advance. Here the names follow such a regular pattern they don't actually tell you anything about specific elements, and just complicate the storage and retrieval of individual elements - Paul Phillips 2012-04-04 05:40
The correct syntax is: details['image' + index]
which can later be accessed through details.image0
, details.image1
etc.
So it should be: details['image' + index] = {prop: val}
details['image' + index] : {
position: position,
title: $slideDiv.children().eq(index).attr("alt")
}
The error is *missing ; before statement * on line details['image' + index] : {
Basit 2012-04-04 05:07
details['image' + index] = {prop: val}
powerbuoy 2012-04-04 05:09
images.each(function(index){
details["image" + (index + 1)] = new Object;
details["image" + (index + 1)].position = position;
details["image" + (index + 1)].title = $slideDiv.children().eq(index).attr("alt")
position += -400;
}) ; //end of .each()
Thank - Basit 2012-04-04 05:20
;
before position += 400
. Don't really see why you'd do that instead of details['image' + (index + 1)] = {prop: val, prop2: val};
though - powerbuoy 2012-04-04 05:44
In Javascript you can access a property one of two ways:
obj.property
is equivalent to
obj["property"]
So in your case you'll want to write it like this:
details["image"+index]