提示用户输入信息,然后对数据进行排序 [英] Prompt user to input information, then sort the data
问题描述
对于一个类项目,我需要在Javascript中创建一个程序,要求用户输入3个名称,然后按字母顺序对名称进行排序并将其打印在屏幕上。
For a class project, I need to create a program in Javascript that asks a user to input 3 names, then sorts the names alphabetically and prints them on the screen.
我已经想出如何为用户创建一个输入数据的提示框,然后我可以让程序打印用户输入的字符串到屏幕。但是,我无法弄清楚如何让Javascript对字符串进行排序。我知道我需要使用一个数组,但我不知道在哪里放置数组,或者如何让它知道用户输入的变量。
I have figured out how to create a prompt box for the user to input the data, and I can get the program to then print the string that the user inputs onto the screen. However, I cannot figure out how to get Javascript to sort the string. I know that I need to use an array, but I'm not sure where to put the array, or how to get it to know user-inputted variables.
这个是我到目前为止的代码:
This is the code I have so far:
<html>
<script>
function disp_prompt()
{
var names=prompt("Please enter three names","Names")
document.getElementById("msg").innerHTML= names
}
</script>
<center><input type="button" onclick="disp_prompt()" value="Click Here"></center>
<br>
<h2><center><div id="msg"></div></center></h2>
</html>
推荐答案
整件事看起来像
var namesToPrompt = 3,
names = [ ];
// as long as namesToPrompt is truthy, prompt for inputs
while( namesToPrompt-- ) {
names.push( prompt('Please enter a name') );
}
// sort our array
names.sort( byName );
// and print it
document.getElementById( 'msg' ).textContent = names.join(',');
function byName( a, b ) {
return a.localeCompare( b );
}
如果你想让用户一次输入所有名字,你可以去喜欢
If you want to let the user enter all names at once, you could go like
var inputNames = prompt( 'Please enter three names','Names' );
document.getElementById( 'msg' ).textContent = inputNames
.split( /,\s+/ ) // split by any amount of white-space characters in a row
.sort( byName )
.join( ',' );
function byName( a, b ) {
return a.localeCompare( b );
}
这篇关于提示用户输入信息,然后对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!