简体   繁体   English

Javascript:如何在do while循环中访问函数范围的变量?

[英]Javascript: How can I access a function-scoped variable within a do while loop?

This do while checks the user input. 这样做会检查用户输入。 However, the console gives me an error, saying "size is not defined" which I think is because size is within the function whereas the while condition is outside the function 然而,控制台给我一个错误,说“大小没有定义”,我认为是因为大小在函数内,而while条件在函数之外

const newGrid = document.getElementById('new-grid');
newGrid.addEventListener('click', createGrid);

const main = document.querySelector('main');

function createGrid() {
    do {
        let size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10);

        const numPx = (600 / size) - 2;
        let px = numPx + 'px';

        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                const div = document.createElement('div');
                div.setAttribute('class', 'grid');
                main.appendChild(div);
                div.setAttribute('style', `width: ${px}; height: ${px}`);
            }
        }

    } while(isNaN(size) || size > 64 || size < 1);

}

您可以在函数内但在do块之外声明变量( let size; ),然后分配它( size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10);do阻塞。

Your options are: 你的选择是:

  • change it to var (const and let are block-scoped, vars are function-scoped and hoisted, more on that here ) 将它更改为var(const和let是块作用域,vars是功能范围和提升,更多内容在这里
  • and more elegant - change let size to const size (because you don't have to reassign it) and move it a level up like so: 并且更优雅 - 将let size更改为const size (因为您不必重新分配它)并将其移动到如此高度:

     function createGrid() { const size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Javascript中,如何从该函数中调用但在其他位置定义的函数中引用函数范围的变量? - In Javascript, how can I reference a function-scoped variable from a function called within that function but defined elsewhere? 修改javascript以显示函数范围的变量 - Modify javascript to expose a function-scoped variable 函数范围变量的常量而不是var? - Const instead of var for function-scoped variables? 如何在JavaScript脚本中循环php变量 - how do I loop a php variable within a javascript script 如何在 JavaScript 的循环中运行异步 $.getJSON 函数? - How do I run an asynchronous $.getJSON function within a loop in JavaScript? 如何在Javascript函数内部的变量中访问变量? - How Do I access a variable inside a variable inside a function in Javascript? Javascript - 如何在函数中使用变量 - Javascript - how do I use a variable within a function 如何从嵌套函数中访问变量? - How can I access a variable from within a nested function? 如何在JavaScript中的for循环中调用函数? - How can i call a function from within a for loop in javascript? Javascript:在箭头 function 内声明的变量无法在 while 循环内更新 - Javascript: variable declared inside arrow function can't be updated within while loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM