不能使用排序方法按升序对单词进行排序?

时间:2017-05-11 08:20:50

标签: javascript arrays sorting

我认为问题是javascript无法识别输入字段必须作为数组

问题出在哪里?

<!DOCTYPE html>
<html>
	<head>
		

		<script>
		
		function myFunction(){
		var longWords = new Array (document.getElementById("text").value);
		longWords.sort(function (a, b) {
		return b.length - a.length;
		})
		document.writeln(longWords);
		}	
		</script>

	</head>

	<body>
	<h1>Enter sentence in field</h1>
		<input id = "text" type = "text"/>
		<button onclick = "myFunction()">Sort text</button>
		
	</body>

</html>

3 个答案:

答案 0 :(得分:3)

您可以使用String#split按空格分割字符串,然后获得包含单词的数组。

function myFunction() {
    var longWords = document.getElementById("text").value.split(' ');
    longWords.sort(function (a, b) {
        return b.length - a.length;
    });
    document.body.appendChild(document.createElement('br'));
    document.body.appendChild(document.createTextNode(longWords));
}	
<h1>Enter sentence in field</h1>
<input id = "text" type = "text"/>
<button onclick = "myFunction()">Sort text</button>

答案 1 :(得分:1)

<!DOCTYPE html>
<html>
	<head>
		

		<script>
		
		function myFunction(){
		var longWords = document.getElementById("text").value.split(' ');
		longWords.sort();
		document.writeln(longWords);
		}	
		</script>

	</head>

	<body>
	<h1>Enter sentence in field</h1>
		<input id = "text" type = "text"/>
		<button onclick = "myFunction()">Sort text</button>
		
	</body>

</html>

答案 2 :(得分:0)

如果您希望对字符串进行排序并转换为数组,请查看下面的代码段

var arr =[];
function convertToArray(text) {
  arr.push(text.split(''));
  console.log(arr);
}



function sortAlphabets(text) {
    console.log(text.split('').sort().join(''));
};
<input type="text" id="name">
<button onclick="sortAlphabets(document.getElementById('name').value);convertToArray(document.getElementById('name').value);">click</button>