2009-08-27 15 views
5

私の頭脳をこの上に置きます。私は以下のコードを持っています:JavaScriptゲームの最初の段階。すべてのオブジェクトは明確に定義されており、DOMインタラクションのためにjQueryを使用しています。パズルは、以下のJSコードを使用して作成されますforループが1回の繰り返しの後に停止するのはなぜですか?

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

+0

'JSON.parse'はどこに定義されていますか? –

+0

これをデバッグするとどうなりますか? – Charlie

答えて

11

同じことをしているかもしれない)。試してください:

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

+1。古典的なJavscriptはつかまった。 – AnthonyWJones

+0

優良 - ありがとう – wheresrhys

1

this.equations = this.json.equations || this.json.equationsが定義されていないので、[]、および、それが

+1

これはループが0反復で実行され、1ループでは実行されないことになります。 – chaos

+1

なぜjson.equationsが定義されていないと思いますか? JSONが入力jsonとparseを解析した場合、それは配列 – AnthonyWJones

+1

でなければなりません。私たちはプロジェクト全体を一目見てみることができないので、仮定を作り、経験を使ってエラーを示唆することができます。私はちょうど私のクリスタルボールを使用しました。確かに、エラーは、forステートメントのグローバル変数として "i"を使用するスコープミスによって引き起こされる可能性が高くなります。 – Rodrigo

0

https://github.com/douglascrockford/JSON-js/blob/master/json2.jsで定義されているあなたはJSON.parseを使用していると仮定すると、[]に割り当てられます、あなたの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文字列を作成するには、同じファイルで定義された:JSON.stringifyが作成されていることを文字列は、あなたがしようとしているものとは異なっていること

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 

注意あなたの問題の原因となっている可能性があります。

関連する問題