简体   繁体   中英

How can I use for loop to count numbers?

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;
}

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:

function countSheep(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).

We can use JavaScript join function as well to achieve this Code

function getCountStr(count) {
    var str =[];
    for (var i = 1; i <= count; i++) {
        str.push(i);
    }
   console.log(str.join(' then '));
}  

There are few issues with your code

function countUp(start) {
  start +=      // <<<<< what's this? It's an incomplete (and useless) statement
  for(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

function countUp(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

 function countUp(start) { // a temporary array to store your numbers var 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 number var stringToDisplay = tmpArr.join(' then '); console.log(stringToDisplay); document.write(stringToDisplay); } countUp(1); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM