我是JavaScript的新手,我为每一卷框架都有两个滚动功能。我无法将每个卷的值都调到框架函数中来调用和使用。如果有人可以帮助,这将是伟大的!提前谢谢,我的代码在下面。
var Bowling = function() {
var STARTING_TOTAL = 0;
ROLL_ONE = Math.floor(Math.random() * 11);
ROLL_TWO = Math.floor(Math.random() * 11);
this.score = STARTING_TOTAL;
var firstScore;
var secondScore;
var totalScore;
Bowling.prototype.firstRoll = function() {
firstScore = ROLL_ONE
return firstScore;
};
Bowling.prototype.secondRoll = function() {
secondScore = Math.floor(Math.random() * 11 - firstScore);
return secondScore;
};
Bowling.prototype.frameScore = function () {
totalScore = firstScore + secondScore
return totalScore;
};
};
答案 0 :(得分:0)
我只能猜到你想要实现的目标。我重构了一点代码:
var Bowling = function () {
var STARTING_TOTAL = 0;
this.score = STARTING_TOTAL; // remains unused; did you mean "totalScore"?
this.firstScore = 0;
this.secondScore = 0;
};
Bowling.prototype.firstRoll = function () {
this.firstScore = Math.floor(Math.random() * 11);
return this.firstScore;
};
Bowling.prototype.secondRoll = function () {
this.secondScore = Math.floor(Math.random() * 11 - this.firstScore);
return this.secondScore;
};
Bowling.prototype.frameScore = function () {
this.totalScore = this.firstScore + this.secondScore
return this.totalScore;
};
// now use it like this:
var bowling = new Bowling();
console.log(bowling.firstRoll());
console.log(bowling.secondRoll());
console.log(bowling.frameScore());

但是,在我的方法中,firstScore
和secondScore
是公共属性。
答案 1 :(得分:0)
要解决为什么第二次滚动可能是否定的问题:如您的代码当前所示,如果第二次滚动小于第一次滚动,则结果将为负数。如果你想要它,那么如果第一次滚动是6,第二次滚动将是0到4之间的数字,尝试类似:
function randomInt(maxNum) {
return Math.floor(Math.random() * maxNum)
}
var maxRoll = 11
var rollOne = randomInt(maxRoll)
var rollTwo = randomInt(maxRoll - rollOne)
console.log(rollOne)
console.log(rollTwo)
反复按“运行代码段”以查看其是否有效。
我所做的改变:
我创建了一个函数randomInt
,它给出了一个从0到某个最大数的随机数。这使您无需两次编写相同的代码。
我创建了一个变量maxRoll
来跟踪最高可能的滚动。
我从第一次滚动中减去maxRoll
以确定第二次滚动的最大数量应该是什么(maxRoll - rollOne
)。然后将其提供给randomInt
。