gpt4 book ai didi

Javascript - 子 block 中的变量重新定义//变量遮蔽

转载 作者:行者123 更新时间:2023-12-01 01:49:31 24 4
gpt4 key购买 nike

我试图了解 Javascript 如何处理当前作用域的子 block 中的 let 变量的重新声明。

let - JavaScript | MDN says:

Variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks.

如果我们尝试这样做,它会按预期正常工作:

function letTest() {
let x = 1;

for(var i = 0; i < 1; i++) {
console.log(x); // logs - 1
}
}

另一个例子。现在,我使用 for 子 block 为 0let 变量分配一个新值,并遍历 for > 循环。这也按预期工作。

function letTest() {
let x = 5;
console.log(x); // logs – 5

for( x = 0; x < 12; x++) {
console.log(x); // logs – 0, 1, 2, 3, 4, 5, 6, … 10, 11
}

console.log(x); // logs - 12
}

但是,当我们通过在 for 子内部使用关键字 let 重新声明并向同一个变量 x 分配新值时会发生什么- block :

function letTest() {
let x = 5;
console.log(x); // logs – 5

for( let x = 0; x < 12; x++) {
console.log(x); // logs – 1, 2, 3, 4, 5, 6, … 10, 11
}

console.log(x); // logs - 5
}

这里的机制是什么?到底发生了什么?

为什么let x = 5的值没有改变,为什么现在有2个同名的let变量?

最佳答案

let 语句创建一个 block 作用域变量。

function letTest() {
let x = 5;
console.log(x); // x = 5 (same 'x')

for(let x = 0; x < 12; x++) {
console.log(x); // x = 1, 2, …, 10, 11 (different 'x')
}

console.log(x); // x - 5 (same 'x')
}

while var 语句创建函数作用域变量。

function varTest() {
var x = 5;
console.log(x); // x = 5

for(var x = 0; x < 12; x++) {
console.log(x); // x = 1, 2, …, 10, 11
}

console.log(x); // x = 12 ('x' from the for-loop)
}

关于Javascript - 子 block 中的变量重新定义//变量遮蔽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51663070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com