2016-04-07 7 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機能は、それが実際に次の2つの方法でこれを修正することができundefined

を返すされることを意味し、任意の値を返すされていないため、これが起こっている理由は次のとおりです。

  1. 変更document.write(printArray(a) + "</br>");printArray(a);document.write("<br/>")へ]
  2. document.writeの代わりにprintArrayに文字列を返し、他のコードをそのまま使用してください。

第二の方法は、より多くの推奨であり、またdocument.body.innerHTMLか何かそのような

を設定してみてください、document.writeを使用すると、いずれかの推奨されないことに注意してくださいだけでなく、将来の参照のためにこれらを読ん勧め:

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++; 
    } 
} 
関連する問題