数组仅显示最后一组输入

时间:2014-02-11 23:51:44

标签: javascript arrays

//global variable
counter=0;
var highestAvg=0;
var average = new Array(); 
var studObj = new Array(); 
var teachObj = new Array(); 
//Objects
var student = {
    studName:"", 
    studentId:"", 
    courses:['a', 'b', 'c', 'd'], 
    marks:[]}

var teacher = {
    profName:"", 
    course:"", 
    office:"", 
    email:""}

for(var i=0; i<30; i++)
{
    studObj[i] = Object.create(student);
    var check = prompt('Please enter students name(!!! to exit): ','');
    if(check !== '!!!')
    {
        studObj[i].studName = check;
        studObj[i].studentId = prompt('Please enter student ID: ','');
        var total=0;
        for(var j=0; j<4; j++)
        {
             studObj[i].marks[j] = prompt('Please enter student marks for ' + studObj[i].courses[j] + ' : ','');
            if(studObj[i].marks[j] > 100 || studObj[i].marks[j] < 0)
            {
                alert("Incorrect mark, please enter a correct mark!")
                j--;
            }
            else
            {
            total += Number(studObj[i].marks[j]);   
            }
        }
        average[i] = total/4;
        counter++;
    }
    else
    {
        break;
    }
    alert(average[i]);
}

var highestAvg = Number(average[0]);
for(var x=1; x<counter; x++)
{
    if((Number(average[x])) > highestAvg)
    {
        highestAvg = average[x];
        var z=x
    }
}
alert(highestAvg);

alert('The student with the highest overall average is: \nStudent Name: ' + studObj[z].studName + '\nStudent ID: ' + studObj[z].studentId + '\nCourses: ' + studObj[z].courses + '\nMarks: ' + studObj[z].marks + '\nAverage Mark: ' + average[z]);

我不知道为什么标记数组不会保存到studObj数组,而是被覆盖。我已经尝试添加另一个数组来保存值,但它再次只显示输入的最后4个标记。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

全局变量!!!

如果在全局范围内声明var或not,它不会改变任何内容。 JavaScript在函数范围内工作,将它遇到的每个var放在最上面,包括你的var i,j,在你的例子中,它变成了一个全局变量。如果发生这种情况,您在页面上包含更多javascript,并且它使用相同的变量名称,因为覆盖了全局范围变量,最终可能会出现问题。 要解决此问题,请改用IIFE

重置循环内的对象,如下所示:

total = 0;
studentCopy = Object.create(student);
studentCopy.marks = []; // resets the browsers' memory for marks[]

将对象添加到数组中会起作用,但将对象推送到数组似乎更好。此外,它更易读,也不太可能引入错误。

studObj[i].marks[j] = prompt('');
studObj[i].studentId = prompt('');

可以是:

studentCopy.marks.push(mark);
students.push(studentCopy);

如果将索引i保存到平均值,则可以改进排序,如:

students.push(studentCopy);
average.push([[total / studentCopy.courses.length], [i]]);

highestAvg = average.sort(function(a, b) {
    return a[0] < b[0]; // use < so the maximum is at index 0
});

您最好的学生将成为最高年级的索引,您可以将其用作学生的索引。然后你需要所有的信息。

bestStudent = students[highestAvg[0][1]];

DEMO: http://jsfiddle.net/tive/s3dQW/