JavaScript数组

求 70,89,78,90,96,79,88,100,56,95 总和,最大值,平均值

最大值

		 var sum=0
		 var attr=[70,89,78,90,96,79,88,100,56,95]
		 for(var i=0;i<attr.length;i++)
		 {
			  if(attr[i]>sum)
			  {
				  sum=attr[i]
			  } 
		 }
		 
		 alert(sum)

总和

		 var sum=0
		 var attr=[70,89,78,90,96,79,88,100,56,95]
		 for(var i=0;i<attr.length;i++)
		 {		  

				  sum=attr[i]+sum
		 }
		 
		 alert(sum)
alert(sum/attr.length)

 平均值 sum/attr.length

最小值,sum=数组中任何一个数

		 var sum=70
		 var attr=[70,89,78,90,96,79,88,100,56,95]
		 for(var i=0;i<attr.length;i++)
		 {
			  if(attr[i]<sum)
			  {
				  sum=attr[i]
			  } 
		 }
		 
		 alert(sum)

 



7,12,16,20,25

给数组插入值;这个值不能与数组的值一样

		<script type="text/javascript">
			var attr = [7,12,16,20,25];	
			var reng=prompt("输入")
			for(var i=0;i<attr.length;i++)
			{
				if(attr[i]==reng)
				{
				break ;	
				}
				if(i==attr.length-1)
				{
				attr[i+1]	=reng;
				}	
			}
			alert(attr)
        </script>

 冒泡排序:按照从小到大的顺序排列
9,8,7,6,5,4,3,2,1

		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;j++)
			{
				if(attr[j]>attr[j+1])
				{
					zj = attr[j];
					attr[j] = attr[j+1]
					attr[j+1] = zj;
				}	
			}	
		}
		alert(attr);
		

 


查找某个值:1,4,5,3,2,7,6,9

		var attr = [1,4,5,3,2,7,3,9];
		var a =3;
		var sy = -1;
		for(var i=0;i<attr.length;i++)
		{
			if(a==attr[i])
			{
				sy = i;
				alert("索引号"+i);
				//alert(i);	
			}
		}
		if(sy==-1)
		{
			alert("没有找到!");	
		}

 



查找数组中某个数字出现的次数

求3,5,7在数组中出现的次数
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

		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,7,4,6,2,6,];
		var c3 = 0;
		var c5 = 0;
		var c7 = 0;
		for(var i=0;i<attr.length;i++)
		{
			switch(attr[i])
			{
				case 3:
					c3++;
					break;
				case 5:
					c5++;
					break;
				case 7:
					c7++;
					break;			
			}	
		}
		alert(c3);
		alert(c5);
		alert(c7);

 

posted @ 2017-10-19 21:42  navyyouth  阅读(117)  评论(0编辑  收藏  举报