我正在尝试创建一个提示框供用户输入数据,但输出应按字母顺序显示单词。
Input: A line of text, using prompt.
Output: The words of the input text, in alphabetical order.
我尝试了以下方法,但似乎对我不起作用:
var textArr = prompt("Enter a line of text: ");
var textArr=string.split();
textArr.sort();
alert(textArr.toString(', '));
最佳答案
我建议:
// 1. gets the text from the user,
// 2. splits that string, on white-space(s), into an array of words
// 3. sorts that array lexicographically (the default),
// 4. joins the array back together with the ', ' string
var textArr = prompt("Enter a line of text: ").split(/\s+/).sort().join(', ');
alert(textArr);
引用文献:
关于JavaScript 用于提示输入和输出按字母顺序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20308440/