数组的几个例子

时间:2022-04-22 23:44:44

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

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

12345678910111213 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]);        }    }

  

 //冒泡排序 

123456789101112131415161718 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]); 

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

12345678910111213141516171819202122 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);    }

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

1234567891011121314151617181920212223242526272829 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]);