2015-05-14 68 views
-2

我在想我的程序有什麼問題。我是否有語法錯誤,或者我在構建數組時排除了某些內容?我很確定問題在於「for」循環,但我似乎找不到它。一些建議或幫助會很好。數組排序內置功能

<HTML> 
 
<!Foundation Page for building our Javascript programs> 
 
<HEAD> 
 
<TITLE>The Foundation Page </TITLE> 
 
<SCRIPT LANGUAGE = "JavaScript"> 
 
function leaderboard() 
 
{ 
 
var temp1; 
 
var temp2; 
 
var temp3; 
 
var temp4; 
 
var temp5; 
 

 
temp1 = 10 
 
temp2 = 20 
 
temp3 = 30 
 
temp4 = 40 
 
temp5 = 50 
 

 
var leader = new Array(5); 
 

 
\t leader[0] = temp1; 
 
\t leader[1] = temp2; 
 
\t leader[2] = temp3; 
 
\t leader[3] = temp4; 
 
\t leader[4] = temp5; 
 
\t 
 
\t leader.sort(function(a,b){return b-a}); 
 
\t var myContent = ''; 
 
\t for (var d=0;d<5;d++) 
 
\t { 
 
\t \t myContent += "score: " + leader[d] + "<BR>"; 
 
\t } 
 
\t document.getElementById("leaderboard").innerHTML = myContent; 
 
} 
 

 
</SCRIPT> 
 
<HEAD> 
 
<BODY> 
 
<BODY BGCOLOUR = "WHITE"> 
 
<H2>The Foundation Page </H2> 
 
<HR> 
 
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT> 
 
</BODY> 
 
</HTML>

+1

有沒有'<東西ID = 「排行榜」>'在你的HTML。 –

回答

0

您正在嘗試的O/P寫入id爲leaderboard元素是不存在的頁面。這是一個錯誤Uncaught TypeError: Cannot set property 'innerHTML' of null - 它不是一個語法錯誤。

所以只需用ID leaderboard創建一個元素如下圖所示

<HTML> 
<!Foundation Page for building our Javascript programs> 
<HEAD> 
<TITLE>The Foundation Page </TITLE> 
<SCRIPT LANGUAGE = "JavaScript"> 
function leaderboard() 
{ 
var temp1; 
var temp2; 
var temp3; 
var temp4; 
var temp5; 

temp1 = 10 
temp2 = 20 
temp3 = 30 
temp4 = 40 
temp5 = 50 

var leader = new Array(5); 

    leader[0] = temp1; 
    leader[1] = temp2; 
    leader[2] = temp3; 
    leader[3] = temp4; 
    leader[4] = temp5; 

    leader.sort(function(a,b){return b-a}); 
    var myContent = ''; 
    for (var d=0;d<5;d++) 
    { 
     myContent += "score: " + leader[d] + "<BR>"; 
    } 
    document.getElementById("leaderboard").innerHTML = myContent; 
} 

</SCRIPT> 
<HEAD> 
<BODY> 
<BODY BGCOLOUR = "WHITE"> 
<H2>The Foundation Page </H2> 
<HR> 
<div id="leaderboard"></div> 
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT> 
</BODY> 
</HTML> 

演示:Fiddle

+0

感謝您的幫助! – Ruben