Incrementing an integer in javascript results in NaN

ε祈祈猫儿з 提交于 2019-12-12 10:18:39

问题


I've tried to debug this but I just don't understand why the variable disp returns as NaN whenever I increment it by one. If anyone could shed some light on why this is happening I'd appreciate it tenfold.

var votePages = new Array();
votePages[0] = "http://minecraftservers.org/vote/100924";
votePages[1] = "http://www.planetminecraft.com/server/revolutionarycraft---ssdfactionsecosurvivalgrief/vote/";
votePages[2] = "http://minecraftservers.net/server/66267/vote/";
votePages[3] = "http://mineservers.com/server/11885/vote";
votePages[4] = "https://minestatus.net/92187-revolutionary-craft/vote";
var disp = 0;

$("#dispVotePage").attr("src", votePages[disp]);

$(document).on('click', '#next', function(){
    $("#dispVotePage").attr("src", '');
    var disp = disp++;
    alert(disp);
    $("#dispVotePage").attr("src", votePages[disp]);
    if (disp !== 0) {
        $("#previous").css('display', 'block');
    }
});

$(document).on('click', '#previous', function(){
    $("#dispVotePage").attr("src", '');
    var disp = disp--;
    $("#dispVotePage").attr("src", votePages[disp]);
    if (disp === 0) {
        $("#previous").css('display', 'none');
    }
});

You'll see that I have alert(disp) in there, its for debugging purposes.


回答1:


Re-declaration of disp. You are declaring it twice:

var disp = 0;                  //Initial Declaration (Global)

... <snip> ...

$(document).on('click', '#next', function(){
    $("#dispVotePage").attr("src", '');
    var disp = disp++;         //Re-declaration. Declares `disp` as a new local variable.
    alert(disp);
    $("#dispVotePage").attr("src", votePages[disp]);
    if (disp !== 0) {
        $("#previous").css('display', 'block');
    }
});

Solution: To use the global disp, do not declare it again. Just use disp++




回答2:


It looks like you are declaring a new disp variable in your functions, even though you have already done so after your array at the top. Get rid of the var disp and just increment or decrement it.




回答3:


looks like it is probably due to var disp = disp++ try disp=disp+1 (without a var) instead. And similarly for decrements. I think it should fix this!



来源:https://stackoverflow.com/questions/19599616/incrementing-an-integer-in-javascript-results-in-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!