Here is my code:
var span = getSpanWithClass("galleria-current");
var slideNumber = span.innerHTML
var imageIDDivs = document.getElementsByClassName("slideshowImage");
var singleimageidDiv = imageIDDivs[slideNumber]
If I use this, sigleImageidDiv doesn't have anything in it. If I just put 0 or 1 in like this:
var singleimageidDiv = imageIDDivs[1]
It works fine. slideNumber is 1, in my test cases.
I have tried these as well:
var singleimageidDiv = imageIDDivs[Number(slideNumber)]
var singleimageidDiv = imageIDDivs[parseInt(slideNumber)]
What is the proper way to use a variable as the index of an array?
-
If you're copying the code directly from the source, you're missing semi-colons at the end of most of your lines. You should fix the syntax of your code before you start looking at other reasons why it might not be working.Wex– Wex2012年06月05日 19:12:23 +00:00Commented Jun 5, 2012 at 19:12
-
2Semicolons are not required in javascript; however, it is definitely good practice to use them.Josh Mein– Josh Mein2012年06月05日 19:13:21 +00:00Commented Jun 5, 2012 at 19:13
-
@JoshMein. Here comes am not I am comments saying: "I uses semicolons only at Stack Overflow..."gdoron– gdoron2012年06月05日 19:17:24 +00:00Commented Jun 5, 2012 at 19:17
-
3What is the innerHTML of that span? That would be the information of interest to solve your problem.Bergi– Bergi2012年06月05日 19:18:10 +00:00Commented Jun 5, 2012 at 19:18
-
1@user1308743. Then it should work. DEMOgdoron– gdoron2012年06月05日 20:06:39 +00:00Commented Jun 5, 2012 at 20:06
3 Answers 3
Parse to int with a radix.
This is the proper way of doing it:
imageIDDivs[parseInt(slideNumber, 10)];
Live DEMO If it doesn't work, then your problem is somewhere else.
BTW indexes work with strings as well. DEMO
2 Comments
innerHTML returns the string inside the element, so if even if you have a number inside your element, it'll be returned as a string, that's why when you use that variable as an index for your array, you don't get a result.
Using parseInt is an acceptable solution, you could also just do something like span.innerHTML * 1, that would force JS to treat the string as an integer.
6 Comments
"1" and 1 are two different indizes for an array.I think, you have an error in your getSpanWithClass function.