gpt4 book ai didi

javascript - JS - 对象构造方法

转载 作者:行者123 更新时间:2023-11-29 10:30:29 25 4
gpt4 key购买 nike

我正在尝试制作一个包含团队积分的对象(如下所示,其中显示“this.update”)。当我运行该程序时,它似乎没有给团队打分,甚至似乎没有评估两个团队的目标。

我希望 team1Points 和 team2Points 属性从 IF 语句派生,如上面的语句或其他解决方案会有所帮助,类似于两队平局得 1 分,赢得 3 分,输得得 0 分。

teamsArray = ["Blue Team", "Red Team"];

function match(team1Name, team2Name, team1Goals, team2Goals) {
this.team1Name = team1Name;
this.team1Goals = team1Goals;
this.team2Name = team2Name;
this.team2Goals = team2Goals;
this.update = function() {
if (team1Goals > team2Goals) {
team1Points = 3;
team2Points = 0;
} else if (team2Goals > team1Goals) {
team2Points = 3;
team1Points = 0;
} else if (team1Goals == team2Goals) {
team1Points = 1;
team2Points = 1;
}
};
this.update();
}

testMatch();

function testMatch() {
var match1 = new match(teamsArray[0], teamsArray[1], 2, 0);
console.log(match1);
}

最佳答案

您的方法创建全局变量而不是属性,您甚至从未调用过它!

为了避免此类问题,我建议改用现代 JavaScript 语法。使用 'use strict'; 指令开始您的脚本以启用严格模式并使用 let 而不是 var 定义变量。如果这样做,浏览器将不允许您在函数内定义全局变量。

至于你的代码的解决方案:

function match(team1Name, team2Name, team1Goals, team2Goals) {
this.team1Name = team1Name;
this.team1Goals = team1Goals;
this.team2Name = team2Name;
this.team2Goals = team2Goals;
this.team1Points = this.team2Points = 0;

this.update = function() {
if (this.team1Goals > this.team2Goals) {
this.team1Points = 3;
this.team2Points = 0;
} else if (this.team2Goals > this.team1Goals) {
this.team2Points = 3;
this.team1Points = 0;
} else if (this.team1Goals == this.team2Goals) {
this.team1Points = 1;
this.team2Points = 1;
}
};
}

并且不要忘记在某处调用 .update()

m = new match("Alpha", "Beta", 0, 2);
m.update();

console.log("Team " + m.team1Name + " has " + m.team1Points + " points.");
console.log("Team " + m.team2Name + " has " + m.team2Points + " points.");

关于javascript - JS - 对象构造方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47319774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com