我是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>
非常感谢 泰德
答案 0 :(得分:2)
您需要在您的数组中调用.sort()
变量products
。 Array 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>
答案 1 :(得分:2)
试试这个
document.getElementById("products").innerHTML = products.sort();
答案 2 :(得分:1)
sort()是一种扩展方法,您不需要将参数传递给。您只需要使用函数名称调用数组名称。您可以查看有关sort()函数here的更多信息。
var products = ["Printer","Tablet","Router","Monitor","Keyboard","Mouse","Webcam","Hard Drive"];
products.sort();
document.getElementById("products").innerHTML = products;
&#13;
<p id="products"></p>
&#13;
答案 3 :(得分:0)
必须是products.sort();
。 Array具有用于排序的内置功能。</ p>
答案 4 :(得分:0)
var products = ["Printer","Tablet","Router","Monitor","Keyboard","Mouse","Webcam","Hard Drive"];
products.sort(); // add this line
document.getElementById("products").innerHTML = products;
&#13;
<p id="products"></p>
&#13;