在执行 JS 代码时,我遇到了一个非常奇怪的问题。我的代码执行没有进入 for
循环,并且控制台中没有错误。当我尝试通过直接在控制台中键入来执行循环时,它正在执行。这是循环:
for(var x = 0; x <= distance; x++) {
var yMinusY1Sq = distance*distance - (x - startX)*(x - startX)
var yMinusy1Cal = parseInt(Math.sqrt(yMinusY1Sq));
console.log(yMinusY1Sq, yMinusy1Cal);
if((yMinusY1Sq == yMinusy1Cal*yMinusy1Cal)) {
y = yMinusY1Cal + startY;
var point = document.createElement("div");
point.className = "output-point";
point.style.height = (grid.offsetHeight/16).toString() + "px";
point.style.width = (grid.offsetWidth/16).toString() + "px";
outputPoints.appendChild(point);
point.style.top = y*oneBoxY;
point.style.left = (x+startX)*oneBoxX;
isodistancePoints.push(point);
}
}
这里,distance
是 >=
1. 循环内的 console.log
没有执行和打印任何内容。同时,如果另一个 console.log
放置在循环之前,则会打印它。那么,到底出了什么问题呢?
编辑
我尝试打印 distance
,这是一个全局变量,就在循环之前,它显示 undefined
,但如果直接使用控制台打印,它会给出 数字
值。这是一个屏幕截图:
这里是初始化和函数的顺序,其他初始化的全局变量工作正常。
var distance;
init();
function init() {
distance = 1;
//Other code
}
$("#run").bind('click', function () {
// some other code
for(var x = 0; x <= distance; x++) {
// some code
}
});
最佳答案
您遇到的问题是在控制台中。记录的是引用,而不是对象的及时值。 From MDN
Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console.
解决方案是
console.log(JSON.stringify(distance))
或
console.log(`${distance}`)
关于Javascript执行未进入for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368556/