Javascript - functions / loops / console.log

时间:2015-08-20 16:50:04

标签: javascript

我对编码很陌生,到目前为止一直很有趣。但我一直在尝试使用函数和循环,并使用console.log打印出来。什么都没问题?还是我完全失去了?

我想要它做的是cupsLeft的值为99。 声明一个名为'bottleStockReporter'的函数。 在函数内部使用console.log()打印出墙上有多少根啤酒。 “墙上挂着99瓶根啤酒.99瓶根啤酒。” 使用while循环调用新函数获取'bottlesLeft'的值,并每次将'bottlesLeft'减少1。

这是我到目前为止所做的:

var bottleStockReporter = function(number)
{
    var bottlesLeft = 99;
    console.log(bottlesLeft) + "bottles of root beer on the wall." + (bottlesLeft) + "bottles of root beer on the wall.";
    for(var bottlesLeft = 99; bottleLeft>0; bottlesLeft = bottlesLeft --);
};
bottleStockReporter(99);

我的输出打印出数字99

4 个答案:

答案 0 :(得分:1)

简单的解决方案。基本上,你传递一个数字,cupsLeft设置为该数字,然后我们向下循环并输出到控制台。

这是您的挑战:测试此功能。如果您传递非号码怎么办?如果传递一个字符串怎么办?如果通过负数怎么办?你如何解释这些案件?

var bottleStockReporter = function(number) {
  for(var bottlesLeft = number; bottlesLeft>0; bottlesLeft--) {
    console.log(bottlesLeft + " bottles of root beer on the wall. " + (bottlesLeft) + " bottles of root beer on the wall.");
  }
};

bottleStockReporter(99); //Loops 99 times

答案 1 :(得分:1)

你应该改变 var bottlesLeft = 99;var bottlesLeft = number;。这样,当您拨打bottleStockReporter(某个号码);时,bottlesLeft每次都不会设置为99。此外,您的for循环会再次将bottlesLeft设置为99,因此您应将其更改为:

for (var num = bottlesLeft; num >= 0; num--) {
    console.log(num + " bottles of beer on the wall. " + num + " bottles of beer.");
}

最后,这样的事情:

function bottleStockReporter(number) {
    for (var num = number; num >= 0; num--) {
        console.log(num + " bottles of root beer on the wall.");
    }
}
bottleStockReporter(99);

如果你想要更加花哨而不输出1 bottles of beer,你可以这样做:

function bottleStockReporter(number) {
    for (var num = number; num >= 0; num--) {
        var str = " bottles ";
        if (num == 1) {
            str = " bottle ";
        }
        console.log(num + str + "of root beer on the wall.");
    }
}
bottleStockReporter(99);

答案 2 :(得分:1)

首先应该遵循问题陈述。

  

声明名为bottleStockReporter

的函数
function bottleStockReporter() {

}
  

使用console.log打印出墙上有多少瓶根。

有点暧昧,但我们假设函数bottleStockReporter将剩下的瓶子数作为参数:

function bottleStockReporter(bottlesLeft) {
    console.log(bottlesLeft + " bottles of beer on the wall. " + bottlesLeft + " bottles of beer.");  
}
  

使用while循环调用新函数以获取' bottlesLeft'的值。并减少' bottlesLeft'每次1点。

假设有99瓶:

var bottles = 99;
while(bottles > 0) { //While loop. Call the function while bottles is positive.
   bottleStockReporter(bottles); //Call function 'bottles' times
   bottles--; //Decrease bottles
}

然后你去。

答案 3 :(得分:0)

但是语法上的一致性呢?

function bottleStockReporter(i) {
    for(var i = 99; i>0; i--) {
        var bottleOrBottles = (i > 1) ? " bottles" : " bottle";         
        console.log(i + bottleOrBottles + " of root beer on the wall.");            
    }
}

bottleStockReporter(99);