使用参数计算JavaScript函数中的平均值

时间:2014-05-12 02:31:21

标签: javascript

我正在尝试定义具有4种不同属性的团队 - 速度,标题,功能和准确性。然后,我想找到这4个属性的平均值,但出于某种原因,当我尝试这样做,或者在属性之间执行任何数学运算时,程序返回undefined。有什么想法吗?

team1 = new team ("Manchester United");
team2 = new team ("Arsenal");
team3 = new team ("Chelsea");
team4 = new team ("New York Rangers");

function soccerGame (team1, team2, team3, team4)  {

var team = function(teamName) {
    this.teamName = teamName;
    this.speed = Math.floor(Math.random() * 10) + 1 ; 
    this.header = Math.floor(Math.random() * 10) + 1 ;
    this.power = Math.floor(Math.random() * 10) + 1 ;
    this.accuracy = Math.floor(Math.random() * 10) + 1 ;
    console.log(this.accuracy + this.power + this.header + this.speed) / 4;
};
}

2 个答案:

答案 0 :(得分:1)

您唯一的问题是您的构造函数包含在soccerGame中,使其成为局部变量。只能在函数范围内访问局部变量。您有两种选择:将team声明放在soccerGame函数中,或删除该函数并实现您计划在其他位置执行的操作。如果您在函数中定义team,则无法传入团队,因此我建议您使用第二个选项。

Demo

答案 1 :(得分:0)

var team = function(teamName) {
    this.teamName = teamName;
    this.speed = Math.floor(Math.random() * 10) + 1 ; 
    this.header = Math.floor(Math.random() * 10) + 1 ;
    this.power = Math.floor(Math.random() * 10) + 1 ;
    this.accuracy = Math.floor(Math.random() * 10) + 1 ;
    console.log(this.accuracy + this.power + this.header + this.speed) / 4;
};


team1 = new team ("Manchester United");
team2 = new team ("Arsenal");
team3 = new team ("Chelsea");
team4 = new team ("New York Rangers");

您的team功能和代码排列很重要。

Working Demo