2009-08-27 128 views
5

把我的大腦絞在這一塊上。我有下面的代碼:JavaScript遊戲的第一階段。所有對象都定義良好,我使用jQuery進行DOM交互。拼圖是用以下JS代碼創建的:爲什麼我的for循環在一次迭代後停止?

var mypuzzle = new puzzle("{solution:'5+6+89',equations:[['5+3=8',23,23],['5+1=6',150,23],['5+3=6',230,23]]}"); 

但是,代碼底部的循環不會比第一次迭代更進一步。任何想法爲什麼?根本沒有錯誤發生。

function equationBox(equation, top, left) {//draggable equation box 
    this.reposition = function() { 
     this.top = 0; 
     this.left = 0; 
    } 
    this.top = 0;//make random 
    this.left = 0;//make random 
    this.equation = equation; 
    if(top && left) { 
     this.top = top; 
     this.left = left; 
    } 
    this.content = this.equation.LHS.string + '<span> = </span>' + this.equation.RHS.string; 
    this.DOM = $('<li>').html(this.content); 
} 


function puzzle(json) { 

    this.addEquationBox = function(equationBox) { 
     $('#puzzle #equations').append(equationBox.DOM); 
    } 

    this.init = function() { 
     //this.drawPuzzleBox(); 
     this.json = JSON.parse(json); 
     this.solution = new expression(this.json.solution || ''); 
     this.equations = this.json.equations || []; 
     var iterations = this.equations.length; 
     for(i=0;i<iterations;i++) 
     { 
      console.log(i); 
      this.addEquationBox(new equationBox(stringToEquation(this.equations[i][0]),this.equations[i][1], this.equations[i][2])); 
     } 
    } 
    this.init(); 
} 
+0

什麼是「迭代」設置? – ChrisF 2009-08-27 13:18:16

+0

定義了「JSON.parse」在哪裏? – 2009-08-27 13:32:34

+0

當你調試這個時會發生什麼? – Charlie 2009-08-27 13:32:57

回答

11

也許您未能範圍的計數器變量是做什麼的,特別是如果你做它的一個習慣(因爲你使用這個名稱的全局變量,以及你在任何代碼寫你任何循環」重新呼叫可能會做同樣的事情)。請嘗試:

for(var i=0;i<iterations;i++) 
+1

+1。經典的Javscript陷阱。 – AnthonyWJones 2009-08-27 13:24:26

+0

非常好 - 謝謝 – wheresrhys 2009-08-27 14:37:15

1

因爲this.equations = this.json.equations || [],並且,因爲this.json.equations是不確定的,它會被分配到[]

+1

這會導致循環運行零迭代,而不是一個。 – chaos 2009-08-27 13:23:11

+1

你爲什麼認爲json.equations是未定義的?如果JSON解析了輸入json的一個段落,那麼它應該是一個數組 – AnthonyWJones 2009-08-27 13:23:50

+1

這是一個機會。由於我們沒有可用的整個項目,所以我們可以做出假設並使用經驗來建議可能的錯誤。我剛剛用我的水晶球。事實上,錯誤可能更有可能是由於在for語句中使用「i」作爲全局變量的範圍錯誤造成的。 – Rodrigo 2009-08-27 13:36:00

0

假設你正在使用JSON.parse截至https://github.com/douglascrockford/JSON-js/blob/master/json2.js定義,看來你的JSON字符串不正確解析:

var string1 = "{solution:'5+6+89',equations:[['5+3=8',23,23],['5+1=6',150,23],['5+3=6',230,23]]}" 
JSON.parse(string1); // throws SyntaxError("JSON.parse") 

當我使用JSON.stringify,在同一個文件中定義,創建從你的對象一個JSON字符串:

var obj = {solution:'5+6+89',equations:[['5+3=8',23,23],['5+1=6',150,23],['5+3=6',230,23]]} 
var string2 = JSON.stringify(obj); 
// {"solution":"5+6+89","equations":[["5+3=8",23,23],["5+1=6",150,23],["5+3=6",230,23]]} 
JSON.parse(string2); // returns a proper object 

請注意JSON.stringify是創建字符串比你想的不一樣使用,這可能是你的問題的原因。