问题描述
我需要向上计数数字,并用介于两者之间的字符串"then"将其打印出来:5然后6然后7然后...像这样.返回时,我对使用参数vs函数名感到非常困惑.我的代码在下面..但是有人可以帮忙吗?
I need to count numbers upward and have it print out with a string "then" in between: 5 then 6 then 7 then... like this. I am very confused with using the parameters vs function name when you return. My code is below.. but could someone help with this?
function countUp(start) {
start +=
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
}
return start;
}
推荐答案
我会做这样的事情:
function countSheep(limit){
for (var i = 1; i < limit; i +=1){
console.log(i + " sheep")
}
}
countSheep(10);
我使用绵羊"代替然后",但是您明白了.既然您只是想产生一个副作用(将"1然后2 .."打印到控制台,则无需构建一个字符串,然后让您的函数将其返回.
I used "sheep" instead of "then", but you get the idea. Since you just want to produce a side effect (print out a "1 then 2.." to the console, you don;t need to build up a string and then have your function return it.
如果您确实想构建一个字符串然后让函数返回它,则可以执行以下操作:
If you did want to build up a string and then have your function return it though, you could do something like this instead:
function countSheep(limit){
var allMySheep = "";
for (var i = 1; i < limit; i +=1){
allMySheep += (i + " sheep, ")
}
return allMySheep;
}
console.log(countSheep(10));
注意:我从1(变量i = 1)开始循环,因为我是在计数绵羊,而不是数字.您可能想从0(var i = 0)开始.
Note: I started my loops at 1 (var i = 1) because I'm counting sheep, not numbers. You'd probably want to start yours at 0 (var i = 0).
这篇关于如何使用for循环对数字进行计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!