gpt4 book ai didi

Javascript 内存节省 - if 语句 var 声明

转载 作者:行者123 更新时间:2023-11-29 17:09:09 25 4
gpt4 key购买 nike

如果变量驻留在不执行的 if 语句中,是否会初始化/存储在内存中,如下所示:

function blah(){
if(something === true){
var blahOne = 1;
var blahTwo = 2;
var blahThree = 3;
} else {
console.log('The above if statement usually won\'t execute');
}
}

我的假设是否定的,但至少可以说 Javascript 是一种古怪的语言。预先感谢您的帮助!

最佳答案

所有 var 声明都被移动到函数的顶部并初始化为未定义。这就是所谓的变量提升。 JavaScript 没有 block 范围,只有函数和全局范围。

你的代码等同于下面的

function blah(){
var blahOne, blahTwo, blahTree;
if(something === true){
blahOne = 1;
blahTwo = 2;
blahThree = 3;
} else {
// blahOne, blahTwo, blahThree are set to undefined
console.log('The above if statement usually won\'t execute');
// But since they have been declared, there's no error in reading them
console.log(blahOne, blahTwo, blahThree);
}
}

关于Javascript 内存节省 - if 语句 var 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22796601/

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