变量问题(这里的i是局部变还是全局变量啊?)

aemyang1987 2008-10-17 02:08:50
<script type="text/javascript">
var name=prompt("姓名")
var i=8;
for (var i=0; i<name.length;i++){
if ("@"==name.charAt(i)){
alert("有");
break;
}
}
alert(i)//这里的i是局部变还是全局变量啊?
if ("@"!=name.charAt(i)){
alert("无");
}
</script>
...全文
55 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
aemyang1987 2008-10-20
  • 打赏
  • 举报
回复
谢谢
Cyril_Tam 2008-10-17
  • 打赏
  • 举报
回复
绝对是全局啦~~~


如果你在这段下面再定交个function,照样能用
dh20156 2008-10-17
  • 打赏
  • 举报
回复
全局!

参见[JavaScript: The Definitive Guide, 4th Edition]

4.3.1 No Block Scope
Note that unlike C, C++, and Java, JavaScript does not have block-level scope. All variables declared in a function, no matter where they are declared, are defined throughout the function. In the following code, the variables i, j, and k all have the same scope: all three are defined throughout the body of the function. This would not be the case if the code were written in C, C++, or Java:

function test(o) {

var i = 0; // i is defined throughout function

if (typeof o == "object") {

var j = 0; // j is defined everywhere, not just block

for(var k = 0; k < 10; k++) { // k is defined everywhere, not just loop

document.write(k);

}

document.write(k); // k is still defined: prints 10

}

document.write(j); // j is defined, but may not be initialized

}
The rule that all variables declared in a function are defined throughout the function can cause surprising results. The following code illustrates this:

var scope = "global";

function f( ) {

alert(scope); // Displays "undefined", not "global"

var scope = "local"; // Variable initialized here, but defined everywhere

alert(scope); // Displays "local"

}

f( );
You might think that the first call to alert( ) would display "global", since the var statement declaring the local variable has not yet been executed. Because of the scope rules, however, this is not what happens. The local variable is defined throughout the body of the function, which means the global variable by the same name is hidden throughout the function. Although the local variable is defined throughout, it is not actually initialized until the var statement is executed. Thus, the function f in the previous example is equivalent to the following:

function f( ) {

var scope; // Local variable is declared at the start of the function

alert(scope); // It exists here, but still has "undefined" value

scope = "local"; // Now we initialize it and give it a value

alert(scope); // And here it has a value

}
This example illustrates why it is good programming practice to place all of your variable declarations together at the start of any function.

87,901

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧