我遇到了一些代码问题,但是我已经设法找到问题所以我几乎找到了修复它的方法。当我将maximum_guesses末尾的数字更改为maximum_guesses1,maximum_guesses2和maximum_guesses3时,代码工作正常。但是,当我复制它并在maximum_guessses结束时更改了数字时,猜测数量应该只计算为3。
如何使下面的代码适用于所有三个maximum_guesses?
maximum_guesses1,maximum_guesses2,maximum_guesses3
number_of_guesses++;
if (number_of_guesses > maximum_guesses3)
{
window.alert("Sorry, you have run out of guesses!");
return;
}
number_of_guesses++;
if (number_of_guesses > maximum_guesses2)
{
window.alert("Sorry, you have run out of guesses!");
return;
}
number_of_guesses++;
if (number_of_guesses > maximum_guesses1)
{
window.alert("Sorry, you have run out of guesses!");
return;
}
我需要将上述所有三个放入一段代码中。 maximum_guesses1在45个猜测停止,maximum_guesses2在40停止,maximum_guesses3在35停止但是当我把它们放在一起时它们不会停止。
答案 0 :(得分:1)
您可能想要做的是将其分离到另一个函数,您的函数应该具有命名空间来构建您的应用程序。您可以使用找到的帮助程序库here执行此操作。
您可以尝试将重构代码尝试为更加结构化的代码:
<强>模块controller.js 强>
dali.util.namespace('myCompany.myApp.module');
myCompany.myApp.module.ClassName = function(maxGuesses) {
this.maxGuesses = maxGuesses;
this.numberOfGuesses = 0;
this.alertMessage = 'Sorry, you have run out of guesses!';
};
myCompany.myApp.module.ClassName.prototype.hasMoreGuessesLeft = function() {
return this.numberOfGuesses < maxGuesses;
};
myCompany.myApp.module.ClassName.prototype.guess = function(guess) {
this.numberOfGuesses++;
if(this.hasMoreGuessesLeft()) {
//do something with the guess?
console.log(guess);
} else {
window.alert(this.alertMessage + ' - ' + this.maxGuesses + ' max.');
}
};
使用它(import module-controller.js):
var maximum_guesses1 = 10;
var instance = new myCompany.myApp.module.ClassName(maximum_guesses1);
var guessAmount = 50;
for (int i = 0; i < guessAmount; i++) {
instance.guess('Ive guessed ' + i + ' time(s)');
}
然后,您可以相应地传递maximum_guesses1
,maximum_guesses2
,maximum_guesses3
。
我希望这会有所帮助。
里斯
答案 1 :(得分:1)
您应该使用Logical Operators来解决此问题。
例如,您的解决方案可能如下所示(如果我理解正确的话):
number_of_guesses++;
if ( number_of_guesses > maximum_guesses1 ||
number_of_guesses > maximum_guesses2 ||
number_of_guesses > maximum_guesses3 ) {
window.alert("Sorry, you have run out of guesses!");
return;
}