简体   繁体   English

if false语句是否始终在javascript中返回未定义?

[英]Does the if false statement always return undefined in javascript?

I am currently developing a website and plan on using JavaScript. 我目前正在开发一个网站,并计划使用JavaScript。

function func() {
    if (false) {
        var a = 'goodbye';
    }
    console.log(a);
}

This above example shows scope and I would like to know how you would prevent this coming out undefined and why this would be the case. 上面的示例显示了范围,我想知道您如何防止未定义的结果以及为什么会这样。

I've researched mdn, w3 schools and varius sites but they are either to specific or too general. 我已经研究了mdn,w3学校和Varus网站,但它们要么具体,要么太笼统。

It would be great for people who use JavaScript regularly but are not the team leads to have this resource - and I plan to use this knowledge to make a web page using front end languages (JavaScript, html, CSS, etc.) 这对于那些经常使用JavaScript但不是团队领导者拥有此资源的人来说非常有用-我计划使用此知识来使用前端语言(JavaScript,html,CSS等)制作网页

online-editor 在线编辑

Please feel free to add more tags if appropriate! 如果合适,请随时添加更多标签!

The reason you're seeing undefined when the condition in that if is false is that var is hoisted to the top of the function and variables get undefined as their default value. if的条件为false时看到undefined的原因是,将var 提升到函数的顶部,并且变量undefined为其默认值。

After hoisting, your code is this: 吊装后,您的代码如下:

function func() {
    var a; // Defaults to `undefined`
    if (false) {
        a = 'goodbye';
    }
    console.log(a);
}

Since the condition is false, a 's default value is never changed. 由于条件是假的, a的默认值永远不会改变。

More about var hoisting on my anemic little blog: Poor misunderstood var 更多关于var提升我的贫血小博客: 可怜的误解var

You are confused with how if statement works, 您对if语句如何工作感到困惑,

if(Condition comes out to true)
{
 This will work
}

Other wise it will not work, you have entered Condition to be false by default so the if block is not executed. 否则它将不起作用,默认情况下,您将Condition输入为false,因此不执行if块。 And as you have defined "a" inside the if block, the variable "a" is never getting defined as the if block is not executed . 而且,正如您在if块中定义的“ a”一样,变量“ a”也永远不会因为if块未执行而定义。 thus you are getting undefined when you are logging a 因此,当您记录一个

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

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