2012-12-30 116 views
0

我的腳本導致瀏覽器凍結並要求我停止腳本。使用螢火蟲我可以看到for循環無止境地循環,並沒有取得任何進展。這裏是循環:For循環不會以Javascript退出,無限循環

for (var x = 1; x < 7; x++) { 
    var y = x; //to stop the value of x being altered in the concat further down 
    var questionidd = "mcq_question_id"; 
    console.log("1 = " + questionidd); 
    var questionid = questionidd.concat(y); // mcq_question_id$ctr the question number 
    console.log("2 = " + questionid); 
    var mcqid = form[questionid].value; // the questions id on db 
    console.log("3 = " + mcqid); 

    var answerr = "mcq_question"; 
    var answer = answerr.concat(y); // mcq_question$ctr the questions chosen answer 
    var chosenanswer = form[answer].value; // the answers value 
    console.log("4 = " + chosenanswer); 
    var amp = "&"; 
    var equal = "="; 
    var questionide = questionid.concat(equal); // "mcq_question_id$ctr=" 
    var questionida = amp.concat(questionide); // "&mcq_question_id$ctr=" 
    var answere = amp.concat(answer, equal); // "&mcq_question$ctr=" 
    if (x = 1) { 
     send.push(questionide, mcqid, answere, chosenanswer); 
    } 
    else { 
     send.push(questionida, mcqid, answere, chosenanswer); 
    } 
} 

更新 - 修正!愚蠢的錯誤是最糟糕的

+4

您若(X = 1)應該是如果(x == 1) – PeterJ

回答

5

if (x = 1) {應該if (x === 1) {

考慮改用能夠抓住這樣的簡單的編程錯誤的IDE。

+0

原諒我beginnerisms,但什麼是IDE? –

+0

http://en.wikipedia.org/wiki/Integrated_development_environment基本上是用來編寫代碼的程序(例如Notepad ++,NetBeans,Eclipse或PHPStorm)。好的人執行一些簡單的「代碼分析」,他們_將捕捉這個錯誤。 – Halcyon

+0

我明白了,我正在使用來自cPanel的內置代碼編輯器 - 而不是最好的。我可能會得到Notepad ++,謝謝你的回答,爲我節省了更多的時間和精力。 –

6
if (x = 1) { 

應該是

if (x === 1) { 

===操作者比較而賦值運算符=分配。許多人犯這個錯誤。 :)

當第一個循環運行時,它將x設置爲零,並且無限次地執行,直到進程終止。這就是爲什麼循環不停止。

+0

'==='更好。幾乎沒有什麼情況下'=='是正確的解決方案。 – Halcyon

+0

@FritsvanCampen好的,謝謝。 – 0x499602D2

+0

我不會說幾乎沒有的情況下,但是在大多數情況下'==='是更好的運算符而不是'==' –

2

看起來你應該有「if(x == 1)」而不是「if(x = 1)」。

您的代碼重複設置X值1,而不是檢查,這相當於1