Why does my for loop stop after one iteration?

Putting your brains on it. I have the code below: the first stages of a game in JavaScript. All objects are clearly defined, and I use jQuery to interact with the DOM. The puzzle is created with the following JS code:

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

However, the loop at the bottom of the code will not go beyond the first iteration. Any idea why? Errors do not occur at all.

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();
}
+5
source share
3 answers

, , ( , , , , ). :

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

this.equations = this.json.equations || [], this.json.equations undefined, []

+1

, JSON.parse, https://github.com/douglascrockford/JSON-js/blob/master/json2.js, , json :/p >

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, , , .

0

All Articles