我试图在JavaScript中编写一个实现此提示的程序
编写JavaScript函数 COUNTDOWN(ⅰ) 它接受一个整数参数并从i返回一个\ countdown“到0,其间出现一个空格 每个号码。 例如,countDown(5)应返回字符串“5 4 3 2 1 0”。至于第一个问题,你可以 想在计算机上测试你的解决方案。
sofar我有这个
var i= "";
function countdown(i)
{
while( i > 0)
{
console.log(integer);
i--;
}
}
countdown();
有人可以帮我编程
答案 0 :(得分:1)
希望这有足够的意义:
function countdown(i) {
//initialize the variable to be returned with the initial i
var ret = i;
//in each iteration, assigns i to i-1 then checks if i >= 0
while (--i >= 0) {
//concatenates a space and the current i value to the return string
ret += ' ' + i;
}
//returns the string
return ret;
}
答案 1 :(得分:1)
我希望您阅读我在代码中添加的评论并学习。
// you write comments in JavaScript with two forward slashes
// i is the integer parameter of your countdown function
// i is passed to countdown when called, i.e. countdown(9)
function countdown(i)
{
// this is an ret string variable that is private to the countdown function
// you can't access ret from outside of this function
var ret = "";
// your loop should include 0 according to your requirements
while( i >= 0)
{
// here you are appending i to your ret string which you'll return at the end of this function
ret += i;// += is a short hand form of saying ret = ret + i
// you want to append an empty space for every i except the last one (0)
if(i > 0) {
ret += " ";
}
i--; // here you are decrementing i
}
return ret;
}
// here you are making the actual call to the function with integer 5
// you are assigning the returned value of your function call to result variable
var result = countdown(5);
// here you are printing your result string variable to the log
console.log(result);
这里使用递归的另一种解决方案(更高级),替代for / while循环,其中函数调用自身:
// here is an implementation using recursion
function countdown(i)
{
if(i<=0)
return i;
return i + " " + countdown(--i);
}
答案 2 :(得分:0)
您希望在倒计时中加入0
,以便
while (i >= 0)
而不是while (i > 0)
,最后会排除0
。
另外,正如上面提到的一些评论,var i = ""
将i
定义为字符串,因此您无法执行i--
之类的操作。您应该将i
定义为整数,例如var i = 5
。
答案 3 :(得分:0)
以下是答案:
function countdown(i) {
answer = '';
while( i >= 0) {
answer = answer + i.toString() + ' ';
i--;
}
return answer;
}
countdown(5);
答案 4 :(得分:0)
以下是使用递归的方法:
//define countdown function
var countdown = function countdown(i) {
//loop while the passed in parameter "i" is >= 0
while (i >= 0) {
//return a space concatenated with the value of i
//and call the countdown function again (by
//concatenating the result) to continue counting down
return ' ' + i + countdown(i -= 1);
}
return ''; //out of loop, return an empty string
};
console.log(countdown(5));
答案 5 :(得分:0)
递归方式;)
var countdown=function(i) {
console.log(i);
i>0 && countdown(i-1);
}
countdown(10);