2013-07-25 60 views
-2

我剛剛就我已經找到的答案發表了評論;不過,我最近創建了一個帳戶,並沒有所需的聲譽。答案是這樣的鏈接:使用循環收集變量

Calculate average of 5 numbers using 2 functions and onchange event handlers

如果向下滾動,它是由RobG給出了答案。在他的腳本中,他提到你可以在循環中收集變量而不是手動調用變量,但他沒有說明如何做到這一點。如果有人可以給我一些關於如何做到這一點的見解,將不勝感激。

在此先感謝,因爲我花了近7個小時試圖弄清楚這一點。

這裏是從另一個頁面的代碼:

function calcAvg(one, two, three, four, five) { 

    // Note that these could be collected using a loop 
    var one = document.totalf.one.value; 
    var two = document.totalf.two.value; 
    var three = document.totalf.three.value; 
    var four = document.totalf.four.value; 
    var five = document.totalf.five.value; 

    // At this point you'd normally validate the values retrieved from 
    // the form and deal with any junk (remove it, stop processing, 
    // ask for another value, etc.) 

    // pass values to performCalc and store result 
    var average = performCalc([one, two, three, four, five]); 

    // Now do something with the result 
    document.totalf.res.value = average; 

    // There's no need for a return statement as 
    // the function doesn't need to return a value 
    // Though an empty return statement is harmless 
    // return 
     } 
+5

這是一個註釋現有的答案。 –

+2

@limelights這個問題本來可以做得更好(其他代碼可能已經被複制過,但是其他的答案並不包括這裏尋找的答案)。 – Pointy

+0

我想說這個問題可能是有效的,如果你改寫它。因爲它很快就會被關閉。 – Stephan

回答

0

根據我從你的任務的理解,你可以通過以下方式使用數組:

var arr = [] 

for(int i; i<n; i++) 
{ 
    arr[i] = //Whatever the variable must hold 
} 

而且你可以讓一個從輸入對象(一個,兩個,三個,四個,五個)中排列並在循環中使用它們。

1

在他的劇本,他提到,你可以在一個循環,而不是手動調用它們收集變量,但他並沒有說如何做到這一點

它實際上,但在2個步驟。

  1. calcAvg()收集被傳遞給performCalc()Array的變量:

    var average = performCalc([one, two, three, four, five]); 
    

    [...]在這個片段是Array literal,並且在這種情況下,創建了一個newArray與5個的輸入值作爲元素。

    這是類似於使用Array constructor

    var average = performCalc(new Array(one, two, three, four, five)); 
    
  2. performCalc()然後取Array,作爲values參數傳遞,並遍歷它們:

    // Loop over values, note that values are strings so they 
    // need to be converted to numbers before being added 
    for (var i=0, iLen=values.length; i<iLen; i++) { 
    
        // the unary "+" operator will cooerce the value to a number 
        // In real life, the value would be checked before being added 
        // to avoid errors from junk input 
        sum += +values[i]; 
    } 
    
+0

好的,是否可以創建一個變量數組,其中while循環限制了創建的變量數量?唯一的問題是while循環是php中的一個變量的函數,那麼有沒有辦法將php變量轉換爲javascript? – user2618927

+0

@ user2618927該循環基於'Array'的['length'屬性](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)( 'iLen = values.length;我

+0

好吧謝謝 – user2618927