繁体   English   中英

为什么我的变量不起作用,但定义起作用了?

[英]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.logs:

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();

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

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

在另一个解决方案中,您也定义了GridHome来保存片段。 但是请注意GridBlock是在循环外定义的,它也在循环内定义,但这次设置为未定义(NB 引用错误)。 循环内的那个优先......而且它只是未定义的(通常这应该给你一个参考错误)。 因此,在结束时,只有一个DIV附加到这是一个限定OUTSIDE循环中的GridHome。

只是提到使用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>

问候。

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();

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM