2016-04-07 28 views
0

我是JavaScript新手,我正在嘗試編寫一個簡單的函數來使用while語句來打印數組元素,但我在最後得到了一個額外的未定義值。任何幫助將高度讚賞使用while循環在printArray函數中獲取額外的未定義值

代碼是:

var a = [1, 3, 6, 78, 87]; 

function printArray(a) { 

    if (a.length == 0) { 
     document.write("the array is empty"); 
    } else { 
     var i = 0; 
     do { 
      document.write("the " + i + "element of the array is " + a[i] + "</br>"); 

     } 
     while (++i < a.length); 
    } 
} 

document.write(printArray(a) + "</br>"); 

,輸出是:

the 0element of the array is 1 
the 1element of the array is 3 
the 2element of the array is 6 
the 3element of the array is 78 
the 4element of the array is 87 
undefined 

我如何獲得未定義的值?我是否跳過任何​​索引?提前致謝!

回答

3

發生這種情況,是因爲你的printArray功能不返回任何值的原因,這意味着它真的返回undefined

您可以通過兩種方式解決這個問題:

  1. 變化document.write(printArray(a) + "</br>");printArray(a);document.write("<br/>")]
  2. 讓您的printArray返回一個字符串,而不是做document.write並保留您的其他代碼

第二種方式是比較推薦的,也請注意,使用document.write不建議或者,嘗試設置document.body.innerHTML或類似的

東西會推薦閱讀這些以供將來參考,以及:

Array.forEach

Why is document.write a bad practice

+0

感謝一噸....問題解決和解釋... –

0
var a = [1, 3, 6, 78, 87]; 

function myFunction() { 
    var i = 0; 
    while (i < a.length) { 
     document.write("the " + i + "element of the array is " + a[i] + "</br>"); 
     i++; 
    } 
} 
相關問題