首页 > 代码库 > Javascript:变量与数组

Javascript:变量与数组

Javascript变量属于弱类型,即声明一个变量的时候无需指定类型,并且之后可以将任何类型的数值复制给它。

代码整理自w3school:http://www.w3school.com.cn

效果图:

技术分享

示例代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />

<title>Javascript 变量</title>

<head>
  <style>
    body {background-color:#e5e5e5}
    span.red {color:red}
  </style>
</head>

<body>
  <h3>(一)js语句会按照它在html中的位置进行执行。</h3>
  <p>This is a paragraph <span class="red">before</span> script.</p>
  <script>
    document.write("Javascript!");
  </script>
  <p>This is a paragraph <span class="red">after</span> script.</p>

  <h3>(二)js是弱类型</h3>
  <script>
    var x;
    document.write("x="+x);
    document.write("<br/>")
    x=2;
    document.write("x="+x);
    document.write("<br/>")
    x="hello"
    document.write("x="+x);
    document.write("<br/>")
  </script>

  <h3>(三)js定义数组</h3>
  <script>
    var arr = new Array();
    arr[0]=1;
    arr[1]=2;
    arr[2]=3;
    document.write("arr[0]="+arr[0]+" arr[1]="+arr[1]+" arr[2]="+arr[2]+" arr[4]="+arr[4]);

    //其他创建数组的方式:
    document.write("<br/>");
    var arr2 = new Array("Tom","Smith","John");
    var arr3 = ["Tom","Smith","John"];
    document.write("arr2[0]="+arr2[0]);
    document.write("<br/>");
    document.write("arr3[0]="+arr3[0]);
  </script>
  <p>JS中数据不存在“下标越界”的问题。(超过数组大小取值会得到undefine)
  
  <h3>(四)js对象</h3>
  <script>
    //创建对象
    var person = {"firstName":"Will","lastName":"Smith"}
    //取得对象的属性值有两种方式:
    var name1 = person.firstName
    var name2 = person["firstName"]
    document.write("name1:"+name1+",name2:"+name2)
  </script>

  <h3>(五)Undefined 和 Null</h3>
  <script>
    var var1;
    var var2 = null;
    var var3 = "hello"
    document.write("var1="+var1+", var2="+var2+", var3="+var3);
    document.write("<br/>");

    var3 = null;
    document.write("var3="+var3+"<br/>");

  </script>

  <h3>(六)声明变量类型</h3>
  <script>
    var x = new String;
    var y = new Number;
    var z = new Array;

    x="hello"
    y=6
    z=["Tom","John","Smith"]
    
    //输出变量的类型
    document.write("x:"+typeof x+"<br/>");
    document.write("y:"+typeof y+"<br/>");
    document.write("z:"+typeof z+"<br/>");

    x = 2;
    document.write("set x=2, x:"+typeof x+"<br/>");
  </script>
</body>
</html>


Javascript:变量与数组