看以下Java代码
public class tesT { public static void main(String args[]){ for(int i=0;i<3;i++) System.out.println(i); for(i=1;i<=4;i++) System.out.println("this is 2\n"); } }运行会出问题,提示找不到第二个循环体中的循环变量i,这说明了一个所谓局部变量的作用域的问题。
正确输出应该为
0 1 2 this is 2 this is 2 this is 2 this is 2将上面的代码使用C++改写,遇到同样的问题
#include<iostream> using namespace std; int main(){ //int i; for(int i=0;i<3;i++) cout<<i<<endl; for(i=1;i<=4;i++) cout<<"this is 2\n"; return 0; }提示第二个循环中的i出错了。
有趣的是,当我在网上搜索时,发现了以下内容
url:http://blog.csdn.net/sax_157001/article/details/51496678
在VC 6 中,i的作用域范围是函数作用域,在for循环外仍能使用变量i 即: for (int i = 0; i < n; ++i) { //…… } cout<< i<< endl; 可以通过 而 for (int i = 0; i < n; ++i) { //…… } int i = 5; 则编译出错。 在DEV C++ 中,i的作用域仅限于for循环,即: for (int i = 0; i < n; ++i) { //…… } int i = 5; 可以通过 而 for (int i = 0; i < n; ++i) { //…… } cout<< i<< endl; 则编译出错。 在vs.NET 中,两种都能通过,但是若在for循环外使用i是,会给出警告。是个有趣的问题
在python中则不会出现这种问题
###########py -2################# for i in range(3): print i for i in range(4): print "this is 2" ###########py -3################# for i in range(3): print(i) for i in range(4): print( "this is 2")输出
0 1 2 this is 2 this is 2 this is 2 this is 2而在javascript中,同样不需要再次声明变量
<html> <body> <script type="text/javascript"> for(var i=0;i<3;i++) document.write(i+"<br>"); for(i=1;i<=4;i++) document.write("this is 2<br>"); </script> </body> </html>输出
0 1 2 this is 2 this is 2 this is 2 this is 2这是因为JS代码中第一个循环体中的循环变量是局部变量,而第二个循环变量则是全局变量,页面任何地方均可以访问。
这个是JS的特性,只要xx=yyy,则xx自动为变量,无需声明符。
visitor tracker