养成好习惯:先写注释再写代码
基础版:直接写逻辑(平均分=总和/个数)
// 求平均分
var scores = [60, 55, 80, 33, 75, 100];
// 求和,相除
var sum = 0;
var avg;for (var i = 0; i < 6; i++) {sum += scores[i];
}avg = sum / 6;
console.log(avg);
运行结果
升级版:用户设置数值个数+依次输入数值
<!-- 报错:scores未定义 ---> 粗心大意:scores[i]漏掉了[i];没把他当作数组 -->
<script>// 初始化数组// var scores = new Array();var scores = [];// 平均数:求和,相除var sum = 0;var avg = 0;var length = 0;// 输入操作length = parseInt(prompt("请输入你要输入的整数个数:"));// 逻辑体for (var i = 0; i < length; i++) {scores[i] = parseInt(prompt("请输入整数:")); //粗心大意:scores[i]漏掉了[i];没把他当作数组sum += scores[i];}avg = sum / length;// 输出alert('平均分:' + avg);// alert(scores[0]);
</script>
报错:scores未定义 — > 粗心大意:scores[i]漏掉了[i];没把他当作数组
基础知识点–创建数组
// new Array() 创建数组
var clothes1 = new Array(); //空数组
var clothes2 = new Array('dress', 'pants', 'jacket', 'shirt');// 字面量创建数组
var clothes3 = ['dress', 'pants', 'jacket', 'shirt'];
var clothes4 = [];// 保存各种常见的类型的数据
var arr1 = [11, 'wangxiaoxi', [36, 99], 'goo job']// 访问数组元素( 下标索引)
var clothes5 = new Array('dress', 'pants', 'coat', 'jacket', 'shirt');
console.log(clothes5[0]);
console.log(clothes5[1]);
console.log(clothes5[2]);
console.log(clothes5[3]);
console.log(clothes5[4]);