[英]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) {
您的setInterval
和setTimeout
正在創建競爭條件。 您在每個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.