javascript - 使用 javascript 对项目列表进行排序

标签 javascript sorting

我正在做一项类作业,需要完成以下任务:

1 用户在文本框(表单字段)中键入项目列表 2 当用户按下排序按钮时,文本框中的列表被排序 3 从文本框中取出文本并将排序后的文本放回文本框中

请帮忙!

编辑:这是我迄今为止所拥有的,但它不起作用。谢谢大家。

<script type="text/javascript">
    function addName()
    {
    var name2add = document.nameForm.newName.value;
    // is the name 1-15 characters in length?
    if (name2add.length > 15 || name2add.length == 0)
    {
        // no, warn the user
        alert("Name must be between 1 and 15 characters long.");
        // put the focus and selection back in the name text box
        document.nameForm.newName.focus();
        document.nameForm.newName.select();
    } else {
        theSelect = document.nameForm.nameList;
        newVal = theSelect.options.length;
        //alert(name2add + " will be #" + newVal);
        // crate the new Option object to insert into the list
        var newOption = new Option(name2add,newVal);
        // insert the new option into the list
        theSelect.options[newVal] = newOption;
        // clear out the name text field and return the focus there
        document.nameForm.newName.value = "";
        document.nameForm.newName.focus();
    }
    return;
    }
    function deleteName()
    {
        var theSelect = document.nameForm.nameList;
        theSelect.options[theSelect.selectedIndex] = null;
        return;
    }
    </script>

    </head>

    <body>
    <form id="form4" name="nameForm" method="post" action="">
      <p>
        <label>
          <input type="text" name="newName" id="newName" />
        </label>
      </p>
      <p>
          <input type="button" value="Add Name To List" name="addButton" id="addButton" onclick="addName()" />

      </p>
      <p>
        <label>
          <select name="list" size="3" id="nameList" >
          </select>
        </label>
      </p>
    <p>
    <INPUT TYPE="BUTTON" NAME="sort" VALUE="  Sort  " 
    OnClick="sortOptions(document.nameForm.list)">
    </p>
    <p>
    <input type="button" value="Remove Name From List" name="deleteButton" id="deleteButton" onclick="deleteName()" />
    </p>
    </form>

最佳答案

幸运的是,Javascript 提供了一种 native 排序算法,因此您不必自己编写算法。它是 array.sort()。

所以,基本上,从文本框中获取文本,将文本放入数组中。然后,在数组上运行 .sort() ;然后将其放回文本框中。

将文本放入数组中,如果用行分隔,则可以使用 string.split("\n"),如果用逗号分隔,则可以使用 string.split(",")。

var itemsToSort = document.getElementById("text_box")
var arrayToSort = itemsToSort.split("\n")
arrayToSort.sort()
document.getElementById("text_box").value = arrayToSort.join("\n")

ID 为“text_box”的文本框。

关于javascript - 使用 javascript 对项目列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3002973/

相关文章:

javascript - 使用 redux 时 React 主组件被调用两次

javascript - 不要在特定路线上渲染组件

java - html 页面上的验证码图像链接

Python自定义排序

algorithm - 将前 10% 的未排序 RDD 作为 Spark 中的另一个 RDD 返回的有效方法?

javascript - 按字母顺序排列项目列表

javascript - 如何在浮线图中的x轴上显示时间?

javascript - 使用 WebStorm 进行 ECMAScript 2015 开发而无需我自己的 gulp/grunt/webpack 脚本?

javascript - 对象数组的特殊排序

java - 使用索引号一次性对多个数组进行排序?