2014-02-11 83 views
0
//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个标记。我在这里先向您的帮助表示感谢。Array只显示最后一组输入

+0

TIL有被称为东西['prompt'](https://developer.mozilla.org/en-US/docs/Web/API/Window.prompt)在Javascript中。但我建议你不要过度使用目前的过度使用方式。 – bits

+0

这对我来说很好,铬32.0.1700.107米。刚刚从控制台运行它,所有值都分配到正确的点。这个实现的浏览器和版本是什么?(这有点令人讨厌,你应该看看只是使用一个表单...)另外,而不是计数器,我可以建议使用'array.length'? –

+0

您是否尝试过使用Math.max.apply(Math,average)'然后遍历'average'数组来获得学号?那么就不需要'var counter'。 – PHPglue

回答

0

全局变量!!!

如果您在全局范围内声明var或不声明,它不会改变任何内容。 JavaScript在函数作用域上工作,将其遇到的每个变量放在最前面,包括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 
}); 

你最好的学生将是指数附加到您可以用作学生索引的highestAvg。然后你有所有的信息需要。

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

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

+0

谢谢你的帮助! – user2827348