输出一个包含姓名和平均分数的表格

时间:2011-10-12 00:04:17

标签: javascript

    var member1 = prompt("Bowler's Name", "Name");
var member1score1 = prompt("Score from game 1", "");
var member1score2 = prompt("Score from game 2", "");
var member1score3 = prompt("Score from game 3", "");
var memeber1avg = ((memberscore1 + member1score2 + member1score3) / 3);


var member2 = prompt("Bowler's Name", "Name");
var member2score1 = prompt("Score from game 1", "");
var member2score2 = prompt("Score from game 2", "");
var member2score3 = prompt("Score from game 3", "");
var memeber2avg = ((memberscore1 + member1score2 + member1score3) / 3);


var member3 = prompt("Bowler's Name", "Name");
var member3score1 = prompt("Score from game 1", "");
var member3score2 = prompt("Score from game 2", "");
var member3score3 = prompt("Score from game 3", "");
var memeber3avg = ((memberscore1 + member1score2 + member1score3) / 3);


var member4 = prompt("Bowler's Name", "Name");
var member4score1 = prompt("Score from game 1", "");
var member4score2 = prompt("Score from game 2", "");
var member4score3 = prompt("Score from game 3", "");
var memeber4avg = ((memberscore1 + member1score2 + member1score3) / 3);

好的,所以我是js的新手,我知道这可以通过数组更简单地完成...只是不知道如何。另外如何将其写入表格?

1 个答案:

答案 0 :(得分:1)

如何为成员创建对象,并为其提供输入和平均计算的方法:

function Member() {
  this.score = [];
  this.name = prompt("Bowler's Name", "Name");
}

Member.prototype = {

  inputScore: function(cnt){
    for (var i = 0; i < cnt; i++) {
      this.score[i] = parseInt(prompt('Score from game ' + (i + 1), ''), 10);
    }
  },

  getAverage: function() {
    var sum = 0;
    for (var i = 0; i < this.score.length; i++) {
      sum += this.score[i];
    }
    return sum / this.score.length;
  }

};

// create four members and input data
var members = [];
for (var i = 0; i < 4; i++) {
  members[i] = new Member();
  members[i].inputScore(3);
}

// output averages    
for (var i = 0; i < members.length; i++) {
  alert('Average for ' + members[i].name + ' is ' + members[i].getAverage());
}