1)隐式创建
var arr=[值1,值2,值3];
2)直接实例化
var arr=new Array(值1,值2,值3);
var array=new Array(size);
示例:
<script> //1.隐式创建 var arr1 = [‘zhangsan’,’lisi’,’wangwu’,’liuye’]; //2.直接实例化 var arr2 = new Array(‘zhangsan’,’lisi’,’wangwu’,’liuye’); //3.直接实例化并指定数组长度 var arr3 = new Array(4); arr3[0] = ‘zhangsan'; arr3[1] = ‘lisi'; arr3[2] = ‘wangwu'; arr3[3] = ‘liuye'; </script>
数组的调用与遍历
基本语法:
数组名称[元素小标]
<script> var arr1 = [‘zhangsan’,’lisi’,’wangwu’,’liuye’]; alert(arr1[1]);//输出 lisi </script>
文本小标
文本小标型数据定义方式
示例:
<script> var arr = [‘张三’,’李四’,’王五’]; arr[‘a’] = ‘张飞'; arr[‘b’] = ‘刘备'; arr[‘c’] = ‘关羽'; alert(arr[‘b’]);//可以正常输出刘备 </script>
通过for循环遍历输出arr数组
<script> var arr = [‘张三’,’李四’,’王五’]; for(var i=0;i<arr.length;i++){ document.write(arr[i]+'<hr>’); } </script>
通过for…in…循环遍历arr数组
示例:
<script> var arr = [‘张三’,’李四’,’王五’]; for(var i in arr){ document.write(arr[i]+'<br>’); } </script>