首页 > 解决方案 > 需要帮助确定如何制作脚本以将数字转换为变量并对数组进行排序并显示结果

问题描述

无法确定如何制作脚本以将数字转换为变量并对数组进行排序并显示结果。需要它将用户输入的数字转换为变量。另外,希望按降序对数组结果进行排序。

这是我的代码:

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>

标签: javascript

解决方案


现在您正在向 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>


推荐阅读