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

js中的数组--动态的哈,不需要预先制定大小的,数组的一些例子,数组是要new的哈
js数组动态的放数据
 var arr = new Array();
        arr[0] = 3;
        arr[1] = "ddddddd";
        arr[2] = true;


一个简单的数组例子;
<script type="text/javascript" language="javascript">
        var arr = new Array();
        arr[0] = "0";
        arr[1] = "1";
        arr[2] = "2";
        arr[3] = "3";
        arr[4] = "4";
        for (var i = 0; i < arr.length; i++) {
            alert(arr[i]);
        }
    </script>


例子2:求数组中最大的数字
    <script type="text/javascript" language="javascript">
        function GetMax(arr) {
            var max = arr[0];
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] > max) {
                max=arr[i];
                }
        }
        return max;
    }
    var arr1 = new Array();
    arr1[0] = 20;
    arr1[1] = 20;
    arr1[2] = 220;
    arr1[3] = 120;
    arr1[4] = 2;
    alert(GetMax(arr1));
    </script>



例子3, tom|tom1|tom2|tom3格式输出
    <script type="text/javascript" language="javascript">
        function myjoin(arr) {
            if (arr.length <= 0) {
                return "";
            }
            var s = arr[0];
            for (var i = 1; i < arr.length; i++) {
            s+="|"+arr[i];
        }
        return s;
    }
    var arr = new Array();
    arr[0] = "tom0";
    arr[1] = "tom1";
    arr[2] = "tom2";
    arr[3] = "tom3";
    alert(myjoin(arr));
    </script>


例子4, tom,tom1,tom2,tom3倒序输出
<script type="text/javascript" language="javascript">
        function myreverse(arr) {
            for (var i = 0; i < arr.length/2; i++) {
                var temp = arr[i];
                arr[i] = arr[arr.length - i - 1];
                arr[arr.length - i - 1] = temp;
            }
        }
    var arr1 = new Array();
    arr1[0] = "tom0";
    arr1[1] = "tom1";
    arr1[2] = "tom2";
    arr1[3] = "tom3";
    myreverse(arr1);
    alert(arr1);
    </script>


简单声明的方法
var arr = [1,2,3,4];
var arr1 = new Array(2,4,44,3,2,2);