我需要在JS'for'循环中执行if / else条件。具体来说,这就是我被告知要做的事情:
这是我的代码
var numSheep = 4;
var monthsToPrint = 12;
for (var monthNumber = 1; monthNumber <= monthsToPrint; monthNumber++) {
if (numSheep < 10000) {
numSheep *= 4;
console.log("There will be " + numSheep + " sheep after " + monthNumber + " month(s)!");
} else {
numSheep *= 4;
var number = numSheep / 2;
var newNum = numSheep - number;
console.log("Removing " + number + " sheep from the population. Phew!");
console.log("There will be " + newNum + " sheep after " + monthNumber + " month(s)!");
}
}
每当我提交此代码时,我都会从codeschool收到此错误,“您正在调用console.log正确的次数,但没有记录正确的消息。当有更多时,您是否正在将numSheep潜水2超过10000。“
P.S:这是挑战没有。 Codechool上的JavaScript Road Trip Part 2的第5部分。如果您需要登录codeschool并亲自查看,此链接应提供48小时访问权限:http://go.codeschool.com/eO1V6A答案 0 :(得分:2)
如果我把一切都搞定了
numSheep = numSheep/2
,你送走的羊现在是相同的,但是把它存放在一个变量中,发送给了嘘。numSheep *= 4;
的console.log
实际代码看起来像;
var numSheep = 4;
var monthsToPrint = 12;
for (var monthNumber = 1; monthNumber <= monthsToPrint; monthNumber++) {
if (numSheep <= 10000) {
numSheep *= 4;
console.log("There will be " + numSheep + " sheep after " + monthNumber + " month(s)!");
} else {
numSheep = numSheep / 2;
var sentSheep = numSheep;
numSheep *= 4;
console.log("Removing " + sentSheep + " sheep from the population. Phew!");
console.log("There will be " + numSheep + " sheep after " + monthNumber + " month(s)!");
}
}