数组排序:按字母顺序排列和数字排序

时间:2014-09-24 20:04:00

标签: javascript jquery html arrays sorting

我想要一个有文本框的网页。文本框下方有两个按钮,表示“按字母顺序排序”和“按数字排序”。我想要它,以便无论用户在框中输入什么,它都会排序。如果用户输入数字和字母,它将取消排序,并弹出一个提示“不能是字母和数字”。单击“按字母顺序排序”按钮时,JavaScript代码将激活并按字母顺序对单词进行排序。 “按数字排序”按钮也是如此。我似乎无法得到单词/数字来排序。

HTML:

<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>

JavaScript的:

function sortAbc() {
var captureText = document.getElementById('textbox');
captureText.sort();
//Help! How to make alert pop up when numbers and letters are typed?
}

function sortNumber() {
var captureNumb = document.getElementByid('textbox');
captureNumb.sort(function(a, b){return a-b});
//Same problem here! How to make alert pop up when numbers and letters are typed?
}

1 个答案:

答案 0 :(得分:1)

这是一个complet实时样本。

  • 使用正则表达式(.match
  • 检查数字或单词
  • 使用数组函数sort

&#13;
&#13;
function sortAbc() {
   var captureText = document.getElementById('textbox');
   if (captureText.value.match(/(?:^| )[\d]+(?: |$)/)) {
     alert("no digits");
     return;
   }
   var words = captureText.value.split(" ");
   captureText.value = words.sort().join(" ");
}

function sortNumber() {
   var captureNumb = document.getElementById('textbox');
   if (captureNumb.value.match(/[^\s\d]/)) {
     alert("no letters");
     return;
   }
   var numbers = captureNumb.value.split(" ");
   captureNumb.value = numbers.sort(function (a, b) { return a - b }).join(" ");
}
&#13;
<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>
&#13;
&#13;
&#13;