1.求一组数中的所有数的和 和平均值
<script>
//求一组数中的所有数的和 和平均值
var scores = [68,88,78,98,80];
var sum = 0;
for(var i=0;i<scores.length;i++){
sum += scores[i];
}
console.log(sum);
console.log(sum/scores.length);
</script>
2.求一组数中的最大值和最小值,以及所在位置
<script>
var scores = [68,88,78,98,80];
//1.思路
//首先我们认为数组中第0个数是最大
var max = scores[0];
var index = 0;
for (var i = 1; i < scores.length; i++) {
if(max < scores[i]){
index = i;
max = scores[i];
}
}
console.log(max +";"+ index);
</script>
3.将字符串数组用|或其他符号分割
var names=["卡卡西","佐助","鸣人","大蛇丸","雏田","小苏","凤姐","黑崎一护"];
<script>
var names=["卡卡西","佐助","鸣人","大蛇丸","雏田","小苏","凤姐","黑崎一护"];
//卡卡西-佐助-鸣人
var str = "";
for(var i=0;i<names.length;i++){
str += names[i];
if(i != names.length-1){
str += "-";
}
}
console.log(str);
</script>
4.要求将数组中的0项去掉,将不为0的值存入一个新的数组,生成新的数组
<script>
var s = [0,0,0,11,12,13,14];
//思路:我们创建一个新的数组,把原来数组中不为0的元素放到新的数组中
var news = [];
var b = 0;
for(var i=0;i<s.length;i++){
if(s[i] != 0){
news[b++] = s[i];
}
}
console.log(news);
</script>
5.反转数组
<script>
var s = [1,2,3,4,5,6,7];
for(var i=0;i<parseInt(s.length/2);i++){
var tmp = s[i];
s[i] = s[s.length-i-1];
s[s.length-i-1] = tmp;
}
console.log(s);
</script>
6.提示用户输入班级人数,求总成绩,平均值,最高分,最低分
parseInt(prompt("请输入班级人数"))
<script>
var scores = [];
//count用来限定班级人数(10人)
var count = 0;
while(count<10){
//第几个人的成绩
var s = parseInt(prompt("请输入第"+count+"个人的分数"));
scores[count] = s;
count++;
}
console.log(scores);
</script>