javascript - 需要帮助确定如何制作脚本以将数字转换为变量并对数组进行排序并显示结果
问题描述
无法确定如何制作脚本以将数字转换为变量并对数组进行排序并显示结果。需要它将用户输入的数字转换为变量。另外,希望按降序对数组结果进行排序。
这是我的代码:
var x = 0;
var z = 0;
var array = Array();
function hellarray() {
array[x] = document.getElementById("mad").value;
alert(array[x] + " was added to array");
x++;
document.getElementById("mad").value = "";
var e = "<hr/>";
for (var y = 0; y < array.length; y++) {
e += "Element " + y + " = " + array[y] + "<br/>";
}
document.getElementById("sadness").innerHTML = e;
}
function diearray() {
array[z] = document.getElementById("mad").value;
points.sort(function(a, b) {
return b - a
});
document.getElementById("sadness").innerHTML = array[z];
}
<input type="text" id="mad">
<input type="button" id="button1" value="Add" onclick="hellarray();">
<input type="button" id="button2" value="Descending" onclick="diearray();">
<p id="sadness"></p>
解决方案
现在您正在向 DOM 添加元素,然后您尝试对这些 DOM 元素进行排序。将数据和实际视图分开通常是一个好主意。
我建议您首先只向数组中添加元素并对该数组进行排序。然后你有一个单独的函数,它只负责将这个数组呈现给你的用户。
我还将一些函数和变量重命名为比hellarray
,array
和更有意义的名称e
。为您的变量命名在未来对您有意义总是一个好主意!
let listItems = [];
function addToList(event) {
const inputField = document.getElementById("mad");
const inputValue = Number(inputField.value);
// You should do a check that inputValue is actually a number here
// Add element to our list
listItems.push(inputValue)
// From what I understand you want to sort the list imediately
listItems.sort(function(a, b) {
return b - a
});
// Render the list for the user
renderList()
// Clear inputfield
inputField.value = ""
}
function renderList() {
var domList = "";
for (let y = 0; y < listItems.length; y++) {
domList += "Element " + y + " = " + listItems[y] + "<br/>";
}
document.getElementById("sadness").innerHTML = domList;
}
<input type="text" id="mad">
<input type="button" id="button1" value="Add" onclick="addToList();">
<hr/>
<p id="sadness"></p>
推荐阅读
- python - 将numpy 1d数组和3d数组的每个元素相乘的有效方法
- r - 将两列名称合并到另一列中
- python - Sympy:lambdify 使得对数组的操作总是产生数组,也适用于常量?
- html - 有没有办法在没有 CSS Flex 的情况下从上到下与从左到右显示 HTML 列表?
- javascript - 为什么在 Firefox 版本 18.0.1 中输入标签会破坏代码?
- vba - 将 jpg 附加到 Outlook 正文和中心
- html - HTML - if else 有条件“如果选择包含 X,做 Y”
- python - 两个具有收入完整值的数据框
- r - axis.text 字体系列和字体大小的有条件更改会产生不需要的“间隙”
- c++ - 为什么我的递归可变参数模板无法编译?