首页 > 解决方案 > 在 JS 中使用 `sort()` 方法对多个名称进行排序

问题描述

我有 2 个按钮,第一个是命名btnClient的,下面是btnSort. 当我输入 3 个名字时,我想按字母顺序排序。

我必须使用该方法sort(),但它不起作用。

在 HTML 中

<body >
  <h1>Exercise 13</h1>
    <input type="text" id="nameClient" size="30"  />
    <button id='btnClient'>Save client</button>
    <input type="text" id="listSort" size="30"  />
    <button id='btnSort'>List sort</button>
    <script src="script.js"></script>
</body>

在 JS 中

var arrayClient = new Array();

var buttonClient = document.getElementById('btnClient');
var buttonDisplay = document.getElementById('btnSort');

buttonClient.addEventListener('click', addClient);
buttonDisplay.addEventListener('click', display);

function addClient(){

    var i = 0;

    arrayClient[i] = document.getElementById('nameClient');
    i = i + 1;

    document.getElementById('nameClient').value = ' ';
}

function display()
{   

    arrayClient.sort();

}

我的btnSort按钮有问题,没有任何反应,即使点击按钮btnSort

var arrayClient = new Array();

var buttonClient = document.getElementById('btnClient');
var buttonDisplay = document.getElementById('btnSort');

buttonClient.addEventListener('click', addClient);
buttonDisplay.addEventListener('click', display);

function addClient(){

    var i = 0;

    arrayClient[i] = document.getElementById('nameClient');
    i = i + 1;

    document.getElementById('nameClient').value = ' ';
}

function display()
{   

    arrayClient.sort();

}
    <html>
    
    <head>
    
      <script src="Thing.js" type="text/javascript">
      </script>
      <link rel="stylesheet" type="text/css" href="Main.css">
    </head>

     <body >
  <h1>Exercise 13</h1>
    <input type="text" id="nameClient" size="30"  />
    <button id='btnClient'>Save client</button>
    <input type="text" id="listSort" size="30"  />
    <button id='btnSort'>List sort</button>
    <script src="script.js"></script>
</body>


    </html>

标签: javascript

解决方案


单击 bntClient 按钮后,使用 push 方法向数组添加值,

单击排序后,您将看到这些值被排序并显示在控制台中。

您的第二个输入毫无意义。

const arrayClient = []

const buttonClient = document.getElementById('btnClient');
const buttonDisplay = document.getElementById('btnSort');
const firstInput = document.getElementById('nameClient');

buttonClient.addEventListener('click', addClient);
buttonDisplay.addEventListener('click', display);


function addClient() {
  arrayClient.push(firstInput.value.trim());
  firstInput.value = '';
}

function display() {
  arrayClient.sort();
  console.log(arrayClient);
}
<html>

<head>

  <script src="Thing.js" type="text/javascript">
  </script>
  <link rel="stylesheet" type="text/css" href="Main.css">
</head>

<body>
  <h1>Exercise 13</h1>
  <input type="text" id="nameClient" size="30" />
  <button id='btnClient'>Save client</button>
  <input type="text" id="listSort" size="30" />
  <button id='btnSort'>List sort</button>
  <script src="script.js"></script>
</body>


</html>


推荐阅读