繁体   English   中英

JavaScript比较返回相同和不同

[英]JavaScript Comparison returning same and different

我正在比较“当前子”和“新子”。 它从一个php文件获取CurrentSub ,并等待4秒钟,然后NewSub从同一文件获取NewSub

当我运行此代码时,它会弹出并显示相同的警报和不同的警报。

我不知道怎么可能一样却又不同? 我正在打印放在屏幕上的变量,它们是相同的。

任何帮助,将不胜感激。

setInterval(function() {
    var CurrentSub = "<?php echo $Name[1] ; ?>";
    setTimeout(function() {
        var NewSub = "<?php echo $Name[1] ; ?>";
        if (NewSub != CurrentSub) {
            window.alert("different");
            setTimeout(function() {
                $('.subText').html(NewSub);
            }, 200)

            document.getElementById("Sub1Move").style.display = "block";
            document.getElementById("Sub1").style.display = "none";
            $("#Sub1Move").animate({
                marginTop: "-=34px",
            }, 1900, function() {
                document.getElementById("Sub1").style.display = "block";
            });
            setTimeout(function() {
                $("#Sub1Move").stop();
                document.getElementById("Sub1").style.display = "block";
                document.getElementById("Sub1Move").style.display = "none";
                document.getElementById("Sub1Move").style.marginTop = "34px";

            }, 2000);
            var CurrentSub = "<?php echo $Name[1] ; ?>";
        };
        if (NewSub == CurrentSub) {
            window.alert("same");
        };
    }, 4000);

    $('.test').html(NewSub);
    $('.test1').html(CurrentSub);

}, 500);

setTimeout(function() {
    $('.subText').html(CurrentSub);
}, 200);

第一条语句在执行之前:

if (NewSub != CurrentSub) {

以便显示不同的警报。 然后最后是:

var CurrentSub = "<?php echo $Name[1] ; ?>";

所以现在CurrentSub和NewSub相等,因此下面的if语句正确地计算为true:

if (NewSub == CurrentSub) {

您的setIntervalsetTimeout正在创建竞争条件。 您在每个setInterval调用中创建了一个新的setTimeout ,持续了4秒。 最后,在执行第一个setTimeouts之前,您将调用8个新的setTimeouts 这是因为每个setInterval需要500毫秒,而嵌套setTimeout需要4秒钟。 基本上,这段代码很臭,因为您必须在它们已经更改时继续进行比较。 尝试在最后一个结束之前不要执行新的setInterval 因此,请延长setInterval超时或缩短嵌套的setTimeout

问题是在闭包中引用的变量。 以及声明的提升,您的代码将嵌套这样的内容。

function scope1(){
    var CurrentSub // local 1
    function scope2()
    {
       var NewSub // local 2
       if(NewSub comparison CurrentSub)//you think you are referring to "local 1" but since you are redeclaring it on this function  you are actually referring to "local 3"
       {
            CurrentSub IS undefined at this point
       }
       var CurrentSub // local 3 .. redeclaration of a var in local scope, is created as undefined in the beginning of the scope, only to be defined at this point
    }
}

最简单的解决方案是从第二个var CurrentSub删除var ,以允许函数引用外部变量,而不是为内部范围创建新变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM