2016-12-01 84 views
-3

我不熟悉Javascript。 我試圖讓我的數組按字母順序打印,但我嘗試過的所有方法似乎都不起作用。例如array.sort()。 請注意,console.log由於某種原因不能打印。 這裏是我的代碼,我無法讓我的數組按字母順序打印

<!DOCTYPE html> 
<html> 
<body> 
<p id="products"></p> 
<script>        
var products = ["Printer","Tablet","Router","Monitor","Keyboard","Mouse","Webcam","Hard Drive"]; 
document.getElementById("products").innerHTML = products; 
array.sort("products"); 
</script> 
</body> 

非常感謝 特德

+5

嘗試排序它,你_before_它添加到頁面... – Alnitak

+0

對不起,我是新來這個。 –

+0

另外,代碼中沒有console.log。 – csmckelvey

回答

2

您需要在您的陣列上調用.sort(),其變量爲productsArray Sort

var products = ["Printer","Tablet","Router","Monitor","Keyboard","Mouse","Webcam","Hard Drive"]; 
 

 
products.sort(); // add this line 
 

 
document.getElementById("products").innerHTML = products;
<p id="products"></p>

+0

謝謝你的幫助。 –

+0

@ T.ROS樂於幫助,如果這有助於您解決問題,那麼您可以將其標記爲答案。 –

0

它必須是products.sort();。數組具有內置功能進行排序。

2

試試這個 document.getElementById("products").innerHTML = products.sort();

1

排序()是一個擴展方法,你不需要傳遞參數。您只需要使用函數名稱來調用數組名稱即可。您可以看到有關sort()函數here的更多信息。

var products = ["Printer","Tablet","Router","Monitor","Keyboard","Mouse","Webcam","Hard Drive"]; 
 
products.sort(); 
 
document.getElementById("products").innerHTML = products;
<p id="products"></p>

0

var products = ["Printer","Tablet","Router","Monitor","Keyboard","Mouse","Webcam","Hard Drive"]; 
 

 
products.sort(); // add this line 
 

 
document.getElementById("products").innerHTML = products;
<p id="products"></p>