为什么即使没有通过if语句也未定义创建Javascript变量? [英] Why is it that Javascript variables are created undefined even if they don't pass if statement?

查看:71
本文介绍了为什么即使没有通过if语句也未定义创建Javascript变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这个为例.

if (b) b = 1;

参考错误. b未定义.有道理,但如果我这样做...

Reference Error. b is not defined. Makes sense but if I do this...

if (b) var b = 1;

我在控制台中未定义.现在当我查找b时,它显示为未定义.

I get undefined in console. and now when I look up what b is it shows as undefined.

如果我再次尝试执行相同的if语句,因为b既不是true也不是false,它不会通过,它是未定义的,但是我想我的问题是为什么它会显示为undefined? JavaScript是否通过if语句,而不管if语句通过还是失败?谢谢.

If I try to do the same if statement again, it doesn't pass because b is neither true or false, it is undefined, but I guess my question is why does it show up as undefined? Does Javascript go through the if statement regardless if the if statement passes or fails? Thanks.

推荐答案

所有var都被提升到它们所在范围的开头,并将其值初始化为undefined.当执行到达var最初所在的行时,然后设置该值.

All vars gets hoisted to the beginning of the scope they are in, initialising their values to undefined. The value is then set when execution reaches the line the var was in originally.

在第二个示例中,由于varb在遇到if之前被初始化为undefined.认为它与编写以下内容相同

In your second example, b gets initialised as undefined before the if is encountered, due to the var. Think of it as the same as writing the following

var b;
if (b) b = 1;

执行此代码后,b仍将是undefined,因为它的初始值是 falsy ,因此它永远不会进入if块.

After this code is executed, b will still be undefined because it will never run into the if block as the initial value is falsy.

pst 所述,这是JavaScript的一种特定于语言的功能,所以请不要用其他语言编写代码时不会期望出现相同的行为.

As mentioned by pst, this is a language specific feature of JavaScript, so don't expect the same behaviour when writing code in other languages.

这篇关于为什么即使没有通过if语句也未定义创建Javascript变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆