在这件事上绞尽脑汁。我有下面的代码: JavaScript游戏的第一阶段。所有对象都定义良好,我使用jQuery进行DOM交互。拼图是用以下JS代码创建的:
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();
}发布于 2009-08-27 13:18:07
这可能是因为您没有限定计数器变量的作用域,特别是如果您已经养成了这样的习惯(因为您正在使用该名称的全局变量,并且您在所调用的任何代码中编写的任何循环都可能执行相同的操作)。尝试:
for(var i=0;i<iterations;i++)发布于 2009-08-27 13:20:43
因为this.equations = this.json.equations || [],并且由于this.json.equations是未定义的,所以它被赋值给[]
发布于 2009-08-27 13:49:55
假设您使用的是在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字符串时:
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创建的字符串与您尝试使用的字符串不同,这可能是导致问题的原因。
https://stackoverflow.com/questions/1341015
复制相似问题