实战
(1)案例描述:随机生成某产品一年中每天的销售额,并计算某一月日平均销售额以及某一周日平均销售额。
(2)实现思路:
1)假设该产品日销售额区间为(0,10000),运用Math对象的random()方法随机生成区间内的随机数;
2)创建三维数组month用于存放每个月每一周每一天的日销售额数据。
<html>
<head>
<title>计算产品销售额</title>
</head>
<script>
var WeekSales = function()
{
this.month=[];
this.init = init;
this.getAverageSomeMonth = getAverageSomeMonth;
this.getAverageSomeWeek = getAverageSomeWeek;
};
var init=function(month)
{
var i=0;j=0;k=0;
for(i=0;i<month;i++)
{
this.month[i] = [];
for(k=0;k<4;k++)
{
this.month[i][k]=[];
for(j=0;j<7;j++)
{
this.month[i][k][j]=parseInt(Math.random()*10000);
}
}
}
};
function getAverageSomeMonth(month)
{
month = month || 12;
console.log(month+"月的日平均销售额:"+this.month[month-1].map(function(arr)
{return arr.reduce(function (a,b){return a+b;});
}).reduce(function(a,b){return a+b;})/28)
}
function getAverageSomeWeek(month,week)
{
month = month || 12;
week = week||1;
console.log(month+"月第"+week+"周的日平均销售额:"+
this.month[month-1][week-1].reduce(function(a,b){return a+b;})/7);
}
var newWeekSales = new WeekSales();
newWeekSales.init(12);
newWeekSales.getAverageSomeMonth(12);
newWeekSales.getAverageSomeMonth(12,4);
</script>
</html>
运行结果如下(随机的):


我不停奔跑只为追赶当年被寄予厚望的自己
(I kept running just to catch up with myself who had high hopes.)
浙公网安备 33010602011771号