JS查找数组中出现的位置及个数

时间:2022-11-30 06:58:24

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

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

      }

  

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

var attr = [1,4,3,5,9,9,3,2,4,6,2,1,3,5,7,9,0,5,3,5,2,1,5,6,7,8,2,4,6,8,0,5];

      //求3,5,7在数组中出现的次数

      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(c3);

      alert(c5);

      alert(c7);