为什么我的变量不起作用,而定义却起作用?

Why does my variable not work, but the definition does?

我 运行 遇到了这个我无法理解的问题。我正在做一个使用 DOM 操作的练习,以便在 javascript 中创建网格。我定义了一个变量,然后将该变量包含在一个循环中。它只创建了一个 div,但它像我问的那样打印了我的 console.log 16 次。所以我直接在循环内定义了变量,这 16 次都有效。有人可以帮助我理解我似乎不理解的范围概念吗?

这个有效:

let gridHome = document.getElementById('grid');
let grid = function() {
    for (i = 0; i < 16; i++){
        console.log('added a div');
        let gridBlock = document.createElement('div');
        gridBlock.setAttribute('class', 'block');
        gridHome.appendChild(gridBlock);
        console.log('run it again');
    }
}
grid();

这只会创建一个 div,但会运行所有 16 个 console.log:

let gridHome = document.getElementById('grid');
let grid = function() {
    let gridBlock = document.createElement('div')
    for (i = 0; i < 16; i++){
        console.log('added a div');
        gridBlock;
        gridBlock.setAttribute('class', 'block');
        gridHome.appendChild(gridBlock);
        console.log('run it again');
    }
}
grid();

非常感谢任何帮助,谢谢!

let gridHome = document.getElementById('grid');
let grid = function() {
    //let gridBlock = document.createElement('div')
    for (i = 0; i < 16; i++){
        let gridBlock = document.createElement('div') // Use this line here 
        console.log('added a div');
        gridBlock.setAttribute('class', 'block');
        gridHome.appendChild(gridBlock);
        console.log('run it again');
    }
}
grid();

@hashbrowns94 这不仅仅是范围的事情,它是 Javascript。我会继续为你分解它。第一个以这种方式工作; 您定义 gridHome。它将包含在循环内创建的所有 div 片段。因此,每次循环结束时,您都会将 gridHome 与新创建的 div 叠加起来 INSIDE 循环,这样一直持续到循环结束。

在另一个解决方案中,您定义 GridHome 来保存碎片。但是请注意 GridBlock 是在循环外定义的,它也在循环内定义,但这次设置为未定义(N.B 引用错误)。循环内的那个优先..而且它只是未定义的(通常这应该给你一个参考错误)。所以最后,只有一个 div 被附加到 GridHome ,这是定义 OUTSIDE循环。

只是提一下使用 const 而不是 let 如下所示。

const gridHome = document.getElementById('grid');
let grid = function() {
    for (i = 0; i < 16; i++){
        console.log('added a div');
        const gridBlock = document.createElement('div');
        gridBlock.setAttribute('class', 'block');
        gridHome.appendChild(gridBlock);
        console.log('run it again');
    }
}
grid();
.block {
  height: 10px;
  width: 100px;
  background: blue;
  margin: 5px;
}
<div id="grid">

</div>

第二部分 试着玩玩这个以了解真正发生的事情..

let gridHome = document.getElementById('grid');
let grid = function() {
   let gridBlock = document.createElement('div')
    for (i = 0; i < 16; i++){
        console.log('added a div');
        //gridBlock;
        gridBlock.setAttribute('class', 'block');
        gridHome.appendChild(gridBlock);
        console.log('run it again');
    }
}
grid();
.block {
  height: 10px;
  width: 100px;
  background: blue;
  margin: 5px;
}
<div id="grid">

</div>

此致。