Oma*_*ani 0 javascript for-loop
我的脚本导致浏览器冻结并要求我停止脚本.使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
更新 - 修复!愚蠢的错误是最糟糕的
if (x = 1) {
Run Code Online (Sandbox Code Playgroud)
应该
if (x === 1) {
Run Code Online (Sandbox Code Playgroud)
该===运营商相比较,而赋值运算符= 分配.很多人犯了这个错误.:)
当第一个循环运行时,它设置x为零,并且无限地执行,直到进程终止.这就是循环不停止的原因.