簡體   English   中英

如何使用for循環對數字進行計數?

[英]How can I use for loop to count numbers?

我需要向上計數數字,並用介於兩者之間的字符串“ then”將其打印出來:5、6、7,然后……。 返回時,我對使用參數vs函數名稱感到非常困惑。 我的代碼在下面..但是有人可以幫忙嗎?

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 ..”打印到控制台,因此您無需構建字符串,然后讓函數返回它)。

如果您確實想建立一個字符串然后讓函數返回它,則可以執行以下操作:

function countSheep(limit){

    var allMySheep = "";

    for (var i = 1; i < limit; i +=1){
        allMySheep += (i + " sheep, ") 
    }

    return allMySheep;
}

console.log(countSheep(10));

注意:我從1(var i = 1)開始循環,因為我是在計算綿羊,而不是數字。 您可能想從0開始(變量i = 0)。

我們也可以使用JavaScript連接功能來實現此代碼

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

您的代碼很少有問題

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
}

您的代碼中已清理且可以使用的版本

function countUp(start) {
  for(var i = start; i < start + 10; i++) {
    console.log(i + " then ");
  }
}

但是此代碼的末尾將有一個額外的“ then”,例如1 then 2 then ,因此這是將處理此問題的代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM