I’ve been making this little script and for some reason, one of the variables won’t increase its value.
The code looks like this:
function get_swf(mode){
var swf_path;
swf_update(); //Updating max_num
if (location.hash) current = location.hash.replace(/[^0-9.]/g, ""); //Getting only numbers
switch(mode){
case "random":
current = Math.floor((Math.random() * max_num) + 1);
swf_path = "uploads/" + current + ".swf";
break;
case "next":
current += 1;
if(current > max_num) current = 1;
swf_path = "uploads/" + current + ".swf";
break;
case "previous":
current -= 1;
if(current == 0) current = max_num;
swf_path = "uploads/" + current + ".swf";
break;
}
swfobject.embedSWF(swf_path, "lolswf", "800", "400", "9.0.0");
location.hash = current;
}
This code is in a function, variables: current and max_num are global variables.
Everything works as expected except when the case “next” is called. In this case, the variable current is set to value “1” even when it hasn’t reached the max_num. For example, if I set:
max_num = 5 and current = 2
and I call “next” current gets set to 1.
I can’t get my head around it, can you please help me?
Thank you very much!
EDIT
After further examination of my code, I found a line that seems to bug the code.
This line is above the code I have provided. (I have updated the code to the whole function, so you can see)
if (location.hash) current = location.hash.replace(/[^0-9.]/g, ""); //Getting only numbers
What I expected from this line is, that it simply overwrites the current variable, so a user doesn’t always have to start from the beginning. However, why would the current have the value “1” even though it should get increased? And why would the other cases work as expected?
Thank you very much for your time!
The variable:
if it is an integer variable it doesn’t support the replace method. Replace method is a property of strings.
Now, when you execute the line:
It actually converts the variable current to empty or 0.
Now in the switch section with the ‘next’ case, only two statements operate on current:
it increments current, i.e., 0 + 1 = 1
checks if it is more than max, it sets it to 1
In either of the cases you are getting 1 in your current.
Hope that helps.