<!DOCTYPE HTML>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>系好安全带,准备启航</title>
<script type="text/javascript">
var mydate=new Date();
//通过javascript的日期对象来得到当前的日期,并输出。
var y=mydate.getFullYear();
var m=mydate.getMonth();
var d=mydate.getDate();
var weekday=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
var w=mydate.getDay();
document.write(y+"年"+m+"月"+d+"日"+"星期"+weekday[w]
+"班级总分为:"+sum);
//成绩是一长窜的字符串不好处理,找规律后分割放到数组里更好操作哦
var scoreStr = "小明:87;小花:81;小红:97;小天:76;小张:74;小小:94;小西:90;小伍:76;小迪:64;小曼:76";
var num=scoreStr.split(";");
var av=0;
var sum=0;
for(var i=0;i<num.length;i++){
sum+=parseInt(num[i].slice(3,5));}
av=sum/num.length;
</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">
var scoreStr = "小明:87;小花:81;小红:97;小天:76;小张:74;小小:94;小西:90;小伍:76;小迪:64;小曼:76";
var s=scoreStr.split(";");
var sum=0;
var pj=0;
for(var i=0;i<s.length;i++){
sum=sum+parseInt(s[i].substring(3));
}
pj=sum/s.length;
pj=Math.floor(pj);
var rq=new Date();
var week=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
document.write(rq.getFullYear()+"年"+(rq.getMonth()+1)+"月"+rq.getDate()+"日"+" "+week[rq.getDay()]+"  "+"班级的总分为:"+sum+"  "+"班级的平均分为:"+pj);
</script>
</head>
<body>
</body>
</html>
楼上的回答都不专业好吗,其实就是你没有明白slice与substr,substring的区别,slice是对数组进行的操作,substr,substring是对字符串进行的操作,你的代码就写错了。以下是我写的代码,你可以对比参考下:
<!DOCTYPE HTML>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>系好安全带,准备启航</title>
<script type="text/javascript">
var scoreStr = "小明:87;小花:81;小红:97;小天:76;小张:74;小小:94;小西:90;小伍:76;小迪:64;小曼:76";
var s=scoreStr.split(";");
var sum=0;
var pj=0;
for(var i=0;i<s.length;i++){
var index=s[i].indexOf(":");
sum=sum+parseInt(s[i].substr(index+1,2));
}
pj=sum/s.length;
pj=Math.floor(pj);
var rq=new Date();
var week=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
document.write(rq.getFullYear()+"年"+(rq.getMonth()+1)+"月"+rq.getDate()+"日"+" "+week[rq.getDay()]+"  "+"班级总分为:"+pj);
</script>
</head>
<body>
</body>
</html>
变量声明和计算结束以后再进行打印才正确,你输出结果的地方还没有开始声明和操作sum这个变量
在你document.write()的时候,sum还没有出生。怎么会有结果呢?