0

我一直在制作这个小脚本,出于某种原因,其中一个变量不会增加它的值。

代码如下所示:

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;

}

这段代码在一个函数中,变量:current并且max_num是全局变量。一切都按预期工作,除非调用“下一个”案例。在这种情况下,即使变量current没有达到max_num. 例如,如果我设置:

max_num = 5current = 2

我称“下一个”current设置为 1。

我无法理解它,你能帮帮我吗?

非常感谢!

编辑

在进一步检查我的代码后,我发现了一行似乎有错误的代码。这一行在我提供的代码之上。(我已经将代码更新为整个函数,大家可以看看)

if (location.hash) current = location.hash.replace(/[^0-9.]/g, ""); //Getting only numbers

我对这一行的期望是,它只是覆盖了current变量,因此用户不必总是从头开始。但是,为什么current即使它应该增加,它的值也会是“1”?为什么其他情况会按预期工作?

非常感谢您的宝贵时间!

4

3 回答 3

1

变量:

location.hash

如果它是一个整数变量,它不支持替换方法。Replace 方法是字符串的一个属性。

现在,当您执行该行时:

if (location.hash) current = location.hash.replace(/[^0-9.]/g, ""); //Getting only numbers

它实际上将变量 current 转换为空或 0。

现在在带有“下一个”案例的 switch 部分中,只有两个语句对当前进行操作:

  1. 它增加电流,即 0 + 1 = 1

  2. 检查它是否大于最大值,将其设置为 1

在任何一种情况下,您都会在当前获得 1。

希望有帮助。

于 2013-01-15T06:53:29.027 回答
0

如果您只使用整数,则模数始终是一种选择

 case "next":
    current = (current+1)%(max_num+1); // the modulus rollover
    if(current == 0) current = 1; // in the case that the remainder is 0
    swf_path = "uploads/" + current + ".swf";
 break;
于 2013-01-14T22:00:37.623 回答
0

您需要使用 if 和 path 变量交换位置。您所做的是将 current 设置为 1,然后将其添加到您的 swf_path 字符串中。

case "next":
    current += 1;
    swf_path = "uploads/" + current + ".swf";
    if(current > max_num) current = 1;
break;

更新

看起来你正在和以前做同样的事情。在那里使用相同的修复

于 2013-01-14T21:53:42.830 回答