代码之家  ›  专栏  ›  技术社区  ›  00Saad

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

  •  3
  • 00Saad  · 技术社区  · 7 年前

    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);
    
    }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Lionel Rowe    7 年前

    可以声明变量( let size; )在功能内但在功能外 do size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10); )在 阻止。

        2
  •  0
  •   verymadmango    7 年前

    • 将它改为var(const和let是块范围的,var是函数范围的,并被提升,更多的是 here
    • 更优雅-改变 let size const size

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