2017-03-22 22 views
1

我剛開始學習編程,我在線觀看教程,並不明白他如何使用循環。我不明白爲java腳本的每個循環

這是他的榜樣和作品

<!DOCTYPE html> 
<html> 
<head> 
    <title> Random </title> 
    <link rel="stylesheet" href="style.css"/> 
</head> 
<body> 
    <div class="container"> 
    </div> 
    <script> 
    var numbers = [33,54,76,34,2,6]; 
    numbers.forEach(function(number){ 
      document.write(number); 
}); 

    </script> 
</body> 
</html> 

這是我的,不工作

<!DOCTYPE html> 
<html> 
<head> 
    <title> Random </title> 
    <link rel="stylesheet" href="style.css"/> 
</head> 
<body> 
    <div class="container"> 
    </div> 
    <script> 
    var foods = [pie,cake,brownie]; 
    foods.forEach(function(string){ 
    document.write(string); 
}); 


    </script> 
</body> 
</html> 

我曾嘗試與數括號替換的字符串值,但不工作。在正確的代碼中,即使定義的變量是數字,他也可以使用變量編號。

+1

當。在瀏覽器中對JavaScript進行編程,瀏覽一下瀏覽器的JavaScript控制檯窗口總是一個好主意,應該會出現一個錯誤或者像「Uncaught ReferenceError:pie沒有定義」。 – gus27

回答

4

你的問題是餡餅,蛋糕和布朗尼不在引文中。

所有字符串必須被單引號或雙引號包圍。

嘗試:

var foods = ["pie", "cake", "brownie"]; 
foods.forEach(function(str)) { 
    document.write(str); 
}); 

現在,你的腳本將其解釋爲變量名。這些變量都沒有定義,這就是爲什麼你沒有得到你期望的輸出。