数组的几个例子

一维数组:var attr = [1,2,3,4,5,6];只有一个

二维数组:var attr = [
[1,2,3,4],
[5,6,7,8],
[10,11,12,13]
];
alert[大数组][大数组中的某个小组的数值];
一个数组里又有数组

1
2
3
4
5
6
7
8
9
10
11
12
13
var attr = [
        [1,2,3,4],
        [5,6,7,8],
        [9,8,7,6]
    ];
     
    for(var i=0;i<attr.length;i++)
    {
        for(var j=0;j<attr[i].length;j++)
        {
            alert(attr[i][j]);
        }
    }

  

 //冒泡排序 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var attr = [9,8,7,6,5,4,3,2,1];
var zj=0;
     
    //控制比较轮数
    for( var i=0;i<attr.length-1;i++)
        {
        //控制次数
        for(var j=0;j<attr.length-1-i;j++)
        {
            if(attr[j]>attr[j+1])
            {
                zj=attr[j];
                attr[j]=attr[j+1];
                attr[j+1]=zj;
            }
        }
     }
    alert(attr[0]); 

//查找某个值在数组中的位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var attr = [1,4,5,3,2,7,6,9];
     
    var zhao = 8;
     
    var sy = -1;
     
    for(var i=0;i<attr.length;i++)
    {
        if(attr[i]==zhao)
        {
            sy = i;
        }
    }
     
    if(sy==-1)
    {
        alert("没有找到值");
    }
    else
    {
        alert("该元素在"+sy);
    }

//几个变量在数组中出现的次数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var attr = [1,4,3,5,6,7,8,9,0,3,4,5,6,7,8,9,2,3,5,7,6,8,0,2,2,3,8];
     
    var c3=0;
    var c5=0;
    var c7=0;
    var  a=0;
    for(var i=0;i<attr.length;i++)
    {
        switch(attr[i])
        {
            case 3:
                  c3++;
                  break;
             
            case 5:
                  c5++;
                  break;
             
            case 7:
                  c7++;
                  break;
            default:
                  a++;
             
        }
    }
    alert(attr[c3]);
    alert(attr[c5]);
    alert(attr[c7]);
posted @ 2017-04-26 13:57  周全264  阅读(468)  评论(0编辑  收藏  举报