0

我的脚本导致浏览器冻结并要求我停止脚本。使用 firebug 我可以看到 for 循环无休止地循环并且没有取得任何进展。这是循环:

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

3 回答 3

6
if (x = 1) {

应该

if (x === 1) {

===运算符在赋值运算符赋值时进行比较。很多人都会犯这个错误。:)=

当第一个循环运行时,它设置x为零,并且无限循环直到进程终止。这就是循环不会停止的原因。

于 2012-12-30T00:58:48.667 回答
5

if (x = 1) {应该if (x === 1) {

考虑切换到可以捕获此类简单编程错误的 IDE。

于 2012-12-30T00:58:39.043 回答
2

看起来您应该使用“if (x == 1)”而不是“if (x = 1)”。

您的代码反复将 x 设置为值 1,而不是检查它是否等于 1。

于 2012-12-30T01:00:13.740 回答