[英]Javascript - functions/loops/console.log
我对编码非常陌生,到目前为止很有趣。 但是我一直在尝试使用一个函数和for循环在一起,并使用console.log将其打印出来。 一切正确吗? 还是我完全迷路了?
我想要做的是把bottleLeft的值设置为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
简单的解决方案。 基本上,您传递一个数字,将bottleLeft设置为该数字,然后我们向下循环并输出到控制台。
这是您的挑战:测试此功能。 如果您传递非数字怎么办? 如果传递字符串怎么办? 如果传递负数怎么办? 您如何处理这些情况?
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
您应该更改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);
您应该首先按照问题说明开始。
声明一个名为
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
}
然后你去。
但是语法一致性如何呢?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.