如何从HTML中的最低值到最高值的用户输入对列表进行排序

时间:2019-03-22 01:44:35

标签: javascript html list user-input

我正在尝试编写一个代码,该代码将给出列表中数字的总和,平均值,最小值,最大值和频率,并对列表从最低值到最高值进行排序。在其他人的帮助下,我能够获得总和,平均值,最大值,最小值和频率,但无法弄清楚如何从最高值到最低值对列表进行排序。我想要的代码是在代码末尾有一个按钮

.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>

用户可以按其按从最低值到最高值的顺序对列表进行排序。

3 个答案:

答案 0 :(得分:1)

适用于您的情况的简单示例https://www.w3schools.com/howto/howto_js_sort_list.asp

您只需要简单地将其从按字母顺序组织为数字组织即可。在这里,对最低到最高最高到最低的列表进行排序,然后重新排列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>

答案 1 :(得分:1)

因为您使用数字作为列表项值,所以我们可以使用数字数组对它进行排序,如下所示。

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 :(得分:0)

我提供了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>

希望这会有所帮助,