日期:2014-05-16  浏览次数:20395 次

js中理解变量的声明

要点:

?

1,函数内声明的变量,无论在哪里声明,作用域都是函数内,无论if块,for循环内等等

?

2,声明局部变量,必须使用var关键字声明,否则该变量是全局的。谨记

?

从事例加深理解,你可以使用记事本保存为html,浏览器实际运行测试一下

?

例子:

?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <script type="text/javascript">
		function demo1(){
			for(i=0;i<10;i++){//未加var声明,i为全局
			}
		}
		function test1(){
			demo1();
			alert(i);
		}
		function demo2(){
			for(a=0;a<10;a++){//加var声明,局部变量
				var b;		  //局部变量,该变量为函数变量,
			}
			//这里可以使用变量b哦,与java不同
		}
		function test2(){
			demo();
			alert(a);//会报错,因为未声明
		}
  </script>
 </head>
 <body>
  <button onclick="test1();">未加var声明的i为全局变量</button><br />
  <button onclick="test2();">加var声明的a为局部变量</button><br />
 </body>
</html>

?

效果图

?

?

?