<!DOCTYPE HTML>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>系好安全带,准备启航</title>
<script type="text/javascript">
//通过javascript的日期对象来得到当前的日期,并输出。
var Time=new Date();
var weekdy=["日","一","二","三","四","五","六"],
year=Time.getFullYear(),
month=Time.getMonth()+1,
date=Time.getDate(),
day=Time.getDay();
document.write(
"今天是:"+year+"年"+month+"月"+date+"日 星期"+weekdy[day]+"<br>");
//成绩是一长窜的字符串不好处理,找规律后分割放到数组里更好操作哦
var scoreStr = "小明:87;小花:81;小红:97;小天:76;小张:74;小小:94;小西:90;小伍:76;小迪:64;小曼:76";
document.write(scoreStr.split(";")+"<br>");
var sorce=0;
for(var i=0;i<scoreStr.length;i++){
sorce+=parseInt(scoreStr[i].split(":").slice(1));
}
document.write("总分"+sorce);
//从数组中将成绩撮出来,然后求和整,并输出。
</script>
</head>
<body>
</body>
</html>
看下我的代码:
<!DOCTYPE HTML>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>系好安全带,准备启航</title>
<script type="text/javascript">
function getScore() {
var mydate = new Date();
// 分别得到年月日
var year = mydate.getFullYear();
var month = mydate.getMonth();
var day = mydate.getDay();
var week = mydate.getDay();
// 年月日组成字符串
var ymd = year + "年" + month + "月" + day + "日";
var weekArr = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
document.write(ymd + " " + weekArr[week] + "<br/>");
var scoreStr = "小明:87;小花:81;小红:97;小天:76;小张:74;小小:94;小西:90;小伍:76;小迪:64;小曼:76";
// 按“;”进行分割得到数组
var scoreArr = scoreStr.split(";");
// 定义一个总分数
var sumScore = 0;
document.write("班级中分数分数如下:<br/>");
// 打印分数,并对每个人分数进行求和
for(var i=0;i<scoreArr.length;i++) {
var studentInfos = scoreArr[i];
var score = parseInt(studentInfos.split(":")[1]);
document.write(score + "<br/>");
sumScore += score;
}
document.write("班级总分数为:" + sumScore + "<br/>");
// 计算平均分数
var avgScore = sumScore / scoreArr.length;
// 对平均数保留整数
var newAvgScore = Math.round(avgScore);
// 弹框形式打印平均分数
alert(ymd + " " + weekArr[week] + "--班级平均分数为:" + newAvgScore);
document.write(ymd + " " + weekArr[week] + "--班级平均分数为:" + avgScore + "<br/>");
document.write(ymd + " " + weekArr[week] + "--班级平均分数为(四舍五入后):" + newAvgScore);
}
</script>
</head>
<body>
<from>
<input type="button" value="点击获取平均分数" onclick="getScore()" />
</from>
</body>
</html>
var score=0; var arr = scoreStr.split(';'); for(var i = 0; i < arr.length; i++){ var num = parseInt(arr[i].slice(3, 5)); score += num; } document.write("总分"+score);
我修改了一下,原来的代码中 sorce+=parseInt(scoreStr[i].split(":").slice(1)); 这一句会将单个非数字字符传入parseInt函数导致返回NaN。