Javascript执行未进入for循环

标签 javascript for-loop

在执行 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,但如果直接使用控制台打印,它会给出 数字值。这是一个屏幕截图: enter image description here

这里是初始化和函数的顺序,其他初始化的全局变量工作正常。

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/

相关文章:

C++ for循环中途崩溃

c++ - 为什么基于范围的 for 语句通过 auto&& 获取范围?

C程序有趣的行为

javascript - 单击按钮时更改 json 中的值

javascript - React-Native:无法从表单值设置状态

c++ - 我如何将一个 while 循环与一个 for 循环结合起来?

r - 使用 R 替代具有 "dynamic"变量的 for 循环

javascript - 如何创建浏览器扩展以在 Firefox 和 Google Chrome 中显示类似信息栏的 HTML 表单横幅?

javascript - 使用 Bootstrap 模式防止子元素的父 onclick 事件传播

javascript - 在谷歌地图中调整高度