这继续给我TypeError:undefined不是一个对象(评估'grades [2] .length')。帮助
此代码的问题是:编写一个名为compare的JavaScript函数,它接受两个等级数组,如果第一个学生的平均成绩较高,则返回“first”;如果第二个学生的平均成绩较高,则返回“second”
function compare (grades)
{
var sum1 = 0;
var length1 = grades[1].length;
for (i=0; i<grades[1].length; i++)
{
sum1 += grades[1];
var avg1 = sum1/length1;
}
var sum2 = 0;
var length2 = grades[2].length;
for (var i=0; i<grades[2].length; i++)
{
sum2 += grades[2];
var avg2 = sum2/length2;
}
if (avg1 > avg2)
{
return "first";
}
if (avg1 < avg2)
{
return "second";
}
}
答案 0 :(得分:1)
试试这个:
var array1 = [1,2,3,4,5];
var array2 = [1,2,3,4,7];
function compare(arr1 , arr2) {
var aver1 = arr1.reduce(function(a, b) { return a + b; }, 0) / arr1.length;
var aver2 = arr2.reduce(function(a, b) { return a + b; }, 0) / arr2.length;
if(aver1 > aver2) {
alert('First');
} else if (aver1 < aver2) {
alert('Second');
}
}
compare(array1, array2);
注意:我假设你没有使用IE&lt; = 8
.reduce()
是Javascript Arrays的内置函数。如果单击上面的链接到MDN上的文档,您将看到它们提供了一个如何对类似于上面使用的数组求和的示例。
答案 1 :(得分:0)
您可以将自己的功能添加到Array而不是重复自己。
Array.prototype.avg = function(){
// Note: "this" is a special JS variable, contains the array "calling" .avg()
// So this.length is the length of the array, and this[0], this[1],... the data
for(var i=0,l=this.length, sum=0; i<l; ++i) sum+=this[i]
return sum/this.length
}
SallyPerfect = [100,100,100,100,95]; // She always gets good grades
LittleBobbyTables = [60,70,60,70,314.159]; // He plays too many games, but reads xkcd
alert("SallyPerfect avg is "+SallyPerfect.avg());
alert("LittleBobbyTables avg is "+LittleBobbyTables.avg());
var whoIsBetter = (SallyPerfect.avg()>LittleBobbyTables.avg())? "SallyPerfect": "LittleBobbyTables";
// you dont have to repeat yourself here, either, but it would require more code.
alert(whoIsBetter+" had the best average grade");
DEMO:http://jsfiddle.net/bp9hvywe/
当然,如果这是一个家庭作业问题,你应该按照你所说的去做,并使用这些代码中的一些(通过适当的引用或归属)来编写一个返回&#34; first&#34;或&#34;秒&#34;。