是否有一种方法可以将数组的内容显示为有序列表,但在警告框中



我正在编写一个程序,它要求通过文本框输入,然后通过提示询问更多项目。我使用.push方法将输入添加到我拥有的空数组中。在程序结束时,它将显示警报框内的项目,但项目需要按字母顺序排列,并显示为有序列表。我知道这可以使用。map方法来完成数组,但我看到的所有示例都将此显示到页面,而不是在警报中。

这是我正在使用的代码。

let list = [];
function groceryList()
{
text_one = document.getElementById('text1').value;
text_two = document.getElementById('text2').value;
text_three = document.getElementById('text3').value;
list.push(text_one, text_two, text_three);
add = prompt("Enter another item on your grocery list: (Enter 0 to finish)");
while (add !== 0) {
list.push(add);
add = prompt("Enter another item on your grocery list: (Enter 0 to finish)");
if (add == 0) {
break;
}
}
list.sort();
alert(list);
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Grocery List</title>
</head>
<body>
<script type="text/javascript" src="my_list.js" charset="utf-8"></script>
<p>Please use the form below to add 3 items to the grocery list.</p>
<form onsubmit="groceryList()">
<input type="text" id="text1">
<input type="text" id="text2">
<input type="text" id="text3"> <br> <br>
<input type="submit" value="Add to the grocery list">
</form>
</body>
</html>

试试这个:

...
list.sort();
let orderedList = list.reduce((list,item, index)=>{ return `${list}${index+1}. ${item}n`},"");
alert(orderedList);
...

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Grocery List</title>
</head>
<body>
<script type="text/javascript" charset="utf-8">
let list = [];

function groceryList()
{
text_one = document.getElementById('text1').value;
text_two = document.getElementById('text2').value;
text_three = document.getElementById('text3').value;
list.push(text_one, text_two, text_three);

add = prompt("Enter another item on your grocery list: (Enter 0 to finish)");

while (add !== 0) {
list.push(add);
add = prompt("Enter another item on your grocery list: (Enter 0 to finish)");

if (add == 0) {
break;
}
}
list.sort();
alert(list.join('n'));
}  
</script>
<p>Please use the form below to add 3 items to the grocery list.</p>
<form onsubmit="groceryList()">
<input type="text" id="text1">
<input type="text" id="text2">
<input type="text" id="text3"> <br> <br>
<input type="submit" value="Add to the grocery list">
</form>
</body>
</html>

最新更新