gpt4 book ai didi

javascript - : javascript vs C vs Python? 中 if block 中变量的范围是多少

转载 作者:行者123 更新时间:2023-11-30 18:24:38 26 4
gpt4 key购买 nike

这些示例中变量的范围如何?一般情况下它是如何工作的?

javascript

var a = 0;
if(true){
var a = 1;
console.log(a);
}
console.log(a);

C

int a = 0;
if(1){
int a = 1;
printf("%i ", a);
}
printf("%i ", a);

Python

a = 0
if True:
a = 1
print a
print a

最佳答案

输出为:

javascript

var a = 0;
if(true){
var a = 1;
console.log(a); //1
}
console.log(a); //1

C

int a = 0;
if(1){
int a = 1;
printf("%i ", a); //1
}
printf("%i ", a); //0

Python

a = 0
if True:
a = 1
print a #1
print a #1

这是因为 javascriptPython 没有 block 作用域;因此,在 if block 中声明的任何内容与在 block 之外声明的任何内容具有相同的作用域(并且 Python 不会不使用声明)。

C 具有 block 作用域。如果您在 block {...} 内声明静态变量,则在 block 之外无法再访问该变量。

所有 block 类型都是如此,例如forelseelseif...

javascript中,如果您想在 block 内声明独占变量,您可以使用let:

Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks . In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

这里有很多关于 javascript 范围的例子:https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/

关于javascript - : javascript vs C vs Python? 中 if block 中变量的范围是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38173455/

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