我正在尝试制作一个代码,该代码将提供列表中数字的总和,平均,最小,最高和数字频率,并且还将列表从最低值到最高值分类。在其他人的帮助下,我能够获得总和,平均,最大,最小和频率,但无法弄清楚如何将列表从最高值分类为最低值。我想要的代码是在代码末尾设有一个按钮
.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<link rel="stylesheet" type="text/css" href="style.css">
<!--- This only allows the user to input numbers --->
<input type='number' id='input'>
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' disabled="disabled">
<!--- Here we have a title for the list --->
<div class="title">Topics</div>
<!--- This will list all of the numbers --->
<ul id='list'></ul>
<!--- When clicked, this buttons alert the user with the numbers --->
<button id="sum"> Sum </button>
<button id="max"> Max </button>
<button id="min"> Min </button>
<button id="avg"> Avg </button>
<button id="frequency"> Frequency </button>
<div>
<button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
</div>
<script>
let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
let frequency = Object.create(null);
// This will add the input number to the list and clear the input
function addClick() {
var li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
update(input.value);
input.value = "";
add.disabled = "disabled";
}
// This allows the "add to list" button to be turned on/off depending if the user has typed in a number
function enableDisable() {
if (this.value === "") {
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This will calculate and update all variable values
function update(enteredValue) {
frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
sum = 0;
min = Infinity;
max = -Infinity;
var count = 0;
for (var i of list.children) {
let val = +i.textContent;
sum += val;
if (val > max) max = val;
if (val < min) min = val;
count++;
}
avg = sum / count;
}
function frequencyClick() {
let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
}, []).join('n');
alert(text);
}
// This functions will alert the numbers
function sumClick() {
alert("The sum of your numbers is: " + sum);
}
function avgClick() {
alert("The average of your numbers is: " + avg);
}
function minClick() {
alert("The smaller number is: " + min);
}
function maxClick() {
alert("The greater number is: " + max);
}
// Here we add all events
input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
document.getElementById("frequency").addEventListener("click", frequencyClick);
</script>
</body>
</html>
用户可以按下将列表从最低值分类为最高值。
在您的情况下有效的简单示例,https://www.w3schools.com/howto/howto_js_sort_list.asp.asp
您只需将其从字母顺序组织到数字上。在这里,您可以将列表排序最低&amp;最高至最低,然后重新安排DOM上的元素。
低高
function lowHigh() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("list");
switching = true;
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// Start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("li");
// Loop through all list items:
for (i = 0; i < (b.length - 1); i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Check if the next item should
switch place with the current item: */
if (b[i].innerText > b[i + 1].innerText) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark the switch as done: */
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
高低
// Change to
if (b[i].innerText < b[i + 1].innerText)
let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
let frequency = Object.create(null);
// This will add the input number to the list and clear the input
function addClick() {
var li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
update(input.value);
input.value = "";
add.disabled = "disabled";
}
// This allows the "add to list" button to be turned on/off depending if the user has typed in a number
function enableDisable() {
if (this.value === "") {
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This will calculate and update all variable values
function update(enteredValue) {
frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
sum = 0;
min = Infinity;
max = -Infinity;
var count = 0;
for (var i of list.children) {
let val = +i.textContent;
sum += val;
if (val > max) max = val;
if (val < min) min = val;
count++;
}
avg = sum / count;
}
function frequencyClick() {
let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
}, []).join('n');
alert(text);
}
// This functions will alert the numbers
function sumClick() {
alert("The sum of your numbers is: " + sum);
}
function avgClick() {
alert("The average of your numbers is: " + avg);
}
function minClick() {
alert("The smaller number is: " + min);
}
function maxClick() {
alert("The greater number is: " + max);
}
function lowHigh() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("list");
switching = true;
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// Start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("li");
// Loop through all list items:
for (i = 0; i < (b.length - 1); i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Check if the next item should
switch place with the current item: */
if (b[i].innerText > b[i + 1].innerText) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark the switch as done: */
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
// Here we add all events
input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
document.getElementById("frequency").addEventListener("click", frequencyClick);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<link rel="stylesheet" type="text/css" href="style.css">
<!--- This only allows the user to input numbers --->
<input type='number' id='input'>
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' disabled="disabled">
<!--- Here we have a title for the list --->
<div class="title">Topics</div>
<!--- This will list all of the numbers --->
<ul id='list'></ul>
<!--- When clicked, this buttons alert the user with the numbers --->
<button id="sum"> Sum </button>
<button id="max"> Max </button>
<button id="min"> Min </button>
<button id="avg"> Avg </button>
<button id="frequency"> Frequency </button>
<p><button onclick="lowHigh()">Sort</button></p>
<div>
<button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
</div>
</body>
</html>
因为您使用数字作为列表项目值,因此我们可以用这样的数字数组对其进行排序。
var list = document.getElementById('list');
function sort(dir){
var li = list.getElementsByTagName("li");
// populate data into array
var data=[];
for(var a in li) {
if (typeof li[a].innerText !='undefined') data.push(parseInt(li[a].innerText,10));
}
// create sort number function as sort parameter, we need this because default sort function will sort it alphabetically
var sortNum = function (a,b) {
return a - b;
}
// start sorting
if (dir == 'asc') data.sort(sortNum);
else data.sort(sortNum).reverse();
// clear list
while (list.lastChild) {
list.removeChild(list.lastChild);
}
// generate new list items
for (var x=0; x<data.length; x++) {
var new_li = document.createElement("li");
new_li.textContent = data[x];
list.appendChild(new_li);
}
}
<input type="button" value="asc" onclick="sort('asc')"><input type="button" value="desc" onclick="sort('desc')">
<ul id="list">
<li>2</li>
<li>3</li>
<li>16</li>
<li>21</li>
<li>15</li>
</ul>
我提供了2个解决方案;更新版本,该版本不存储并计算每个更新(版本1)和另一个版本,该版本是您自己的扩展(版本2):
版本1:
let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
let items = [];
addItem = () => {
var li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
items.push(+input.value);
input.value = "";
add.disabled = "disabled";
}
// This allows the "add to list" button to be turned on/off depending if the user has typed in a number
function enableDisable() {
if (this.value === "") {
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This functions will alert the numbers
// You can pull these out into functions if you would like.
getSum = () => alert(`The sum of your numbers is: ${items.reduce((acc, v)=>acc+=v,0)}`);
getAvg = () => alert(`The average of your numbers is: ${items.reduce((acc, v)=>acc+=v,0)/items.length}`);
getMin = () => alert(`The smaller number is: ${Math.min(...items)}`);
getMax = () => alert(`The greater number is: ${Math.max(...items)}`);
getAscending = () => alert(JSON.stringify(items.sort(), null, 4));
getDescending = () => alert(JSON.stringify(items.sort((a, b) => b - a), null, 4));
getFrequency = () => alert(
Object.entries(items.reduce((acc, v) => {
if (acc[v]) {
acc[v]++;
} else {
acc[v] = 1;
}
return acc;
}, {})).map(([number, fqy]) =>
`The number ${number} appeared ${fqy} time(s) in the list`
).join("n"));
.title {
font-weight: bold;
margin-top: 1em;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<link rel="stylesheet" type="text/css" href="style.css">
<!--- This only allows the user to input numbers --->
<input type='number' id='input' oninput="enableDisable()">
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' onClick="addItem()" disabled="disabled">
<!--- Here we have a title for the list --->
<div class="title">Topics</div>
<!--- This will list all of the numbers --->
<ul id='list'></ul>
<!--- When clicked, this buttons alert the user with the numbers --->
<button onClick="getSum()"> Sum </button>
<button onClick="getMax()"> Max </button>
<button onClick="getMin()"> Min </button>
<button onClick="getAvg()"> Avg </button>
<button onClick="getFrequency()"> Frequency </button>
<button onClick="getAscending()"> Sort Ascending </button>
<button onClick="getDescending()"> Sort Descending </button>
<div>
<button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
</div>
</body>
</html>
版本2:
var list = document.getElementById("list");
var input = document.getElementById("input");
var add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
var frequency = Object.create(null);
var ascending = [];
var descending = [];
// This will add the input number to the list and clear the input
function addClick() {
var li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
update(input.value);
input.value = "";
add.disabled = "disabled";
}
// This allows the "add to list" button to be turned on/off depending if the user has typed in a number
function enableDisable() {
if (this.value === "") {
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This will calculate and update all variable values
function update(enteredValue) {
frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
sum = 0;
min = Infinity;
max = -Infinity;
var count = 0;
for (var i of list.children) {
let val = +i.textContent;
sum += val;
if (val > max) max = val;
if (val < min) min = val;
count++;
}
avg = sum / count;
ascending = Object.keys(frequency).sort();
descending = Object.keys(frequency).sort((a, b) => b - a);
}
function frequencyClick() {
let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
}, []).join('n');
alert(text);
}
// This functions will alert the numbers
function sumClick() {
alert("The sum of your numbers is: " + sum);
}
function avgClick() {
alert("The average of your numbers is: " + avg);
}
function minClick() {
alert("The smaller number is: " + min);
}
function maxClick() {
alert("The greater number is: " + max);
}
function ascending() {}
function descending() {}
// Here we add all events
input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
document.getElementById("frequency").addEventListener("click", frequencyClick);
document.getElementById("ascending").addEventListener("click", () => alert(JSON.stringify(ascending, null, 4)));
document.getElementById("descending").addEventListener("click", () => alert(JSON.stringify(descending, null, 4)));
.title {
font-weight: bold;
margin-top: 1em;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<link rel="stylesheet" type="text/css" href="style.css">
<!--- This only allows the user to input numbers --->
<input type='number' id='input'>
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' disabled="disabled">
<!--- Here we have a title for the list --->
<div class="title">Topics</div>
<!--- This will list all of the numbers --->
<ul id='list'></ul>
<!--- When clicked, this buttons alert the user with the numbers --->
<button id="sum"> Sum </button>
<button id="max"> Max </button>
<button id="min"> Min </button>
<button id="avg"> Avg </button>
<button id="frequency"> Frequency </button>
<button id="ascending"> Sort Ascending </button>
<button id="descending"> Sort Descending </button>
<div>
<button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
</div>
</body>
</html>
希望这会有所帮助,