How Can I Use For Loop To Count Numbers?
Solution 1:
I would do something like this:
function countSheep(limit){
for (var i = 1; i < limit; i +=1){
console.log(i + " sheep")
}
}
countSheep(10);
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:
functioncountSheep(limit){
var allMySheep = "";
for (var i = 1; i < limit; i +=1){
allMySheep += (i + " sheep, ")
}
return allMySheep;
}
console.log(countSheep(10));
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).
Solution 2:
We can use JavaScript join function as well to achieve this Code
functiongetCountStr(count) {
var str =[];
for (var i = 1; i <= count; i++) {
str.push(i);
}
console.log(str.join(' then '));
}
Solution 3:
There are few issues with your code
- Event Listener For Input's Value Change Through Changing With .val() In Jquery?
- Selecting A Default Value In An R Plotly Plot Using A Selectize Box Via Crosstalk In R, Using Static Html Not Shiny
- I Am Working On An Html 5 Canvas And Trying To Draw Circles On It, But As I Trying To Use A Loop All Disappears
functioncountUp(start) {
start += // <<<<< what's this? It's an incomplete (and useless) statementfor(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
// ^^^^^^^^ why are doing this? you should only write i
}
return start; // you don't need to return anything
}
A cleaned and working version from your code
functioncountUp(start) {
for(var i = start; i < start + 10; i++) {
console.log(i + " then ");
}
}
But this code will have an extra 'then' at the end like 1 then 2 then
, so here's a code that will handle this
functioncountUp(start) {
// a temporary array to store your numbersvar tmpArr = [];
for (var i = start; i < start + 10; i++) {
// store the count into the array
tmpArr.push(i);
}
// display the count by putting ' then ' between each numbervar stringToDisplay = tmpArr.join(' then ');
console.log(stringToDisplay);
document.write(stringToDisplay);
}
countUp(1);
Post a Comment for "How Can I Use For Loop To Count Numbers?"