Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 按字母顺序排序单词的程序

按字母顺序对单词进行排序的 JavaScript 程序

在本示例中,您将学习编写一个 JavaScript 程序,该程序按字母顺序对字符串中的单词进行排序。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 字符串 JavaScript 数组 JavaScript 数组排序()

示例: 按字母顺序对单词进行排序

// program to sort words in alphabetical order
// take input
const string = prompt('Enter a sentence: ');
// converting to an array
const words = string.split(' ');
// sort the array elements
words.sort();
// display the sorted words
console.log('The sorted words are:');
for (const element of words) {
  console.log(element);
}
输出
Enter a sentence: I am learning JavaScript
The sorted words are:
I
JavaScript
am
learning
在上面的例子中,提示用户输入一个句子。
使用split(' ') 方法将句子分割成数组元素(单个单词)。 split(' ') 方法在空格处拆分字符串。
使用sort() 方法对数组的元素进行排序。 sort() 方法按字母顺序和升序对字符串进行排序。 for...of 循环用于遍历数组元素并显示它们。
在这里,我们按字母顺序排序。因此,预期的输出是 amIJavaScriptlearning。但是, am 打印在 IJavaScript 之后。
为什么 I 和 JavaScript 在 am 之前打印?
这是因为 JavaScriptIJ 都是大写的。而且,当我们使用 sort() 方法时,大写字母放在小写字母之前。
我们可以通过仅提供小写输入来验证这一点。
// program to sort words in alphabetical order
// take input
const string = prompt('Enter a sentence: ');
// converting to an array
const words = string.split(' ');
// sort the array elements
words.sort();
// display the sorted words
console.log('The sorted words are:');
for (const element of words) {
  console.log(element);
}
输出
Enter a sentence: i am learning javascript
The sorted words are:
am
i
javascript
learning
在这里,我们现在得到了预期的输出。
注意: 您还可以将数组元素转换回字符串并使用 join() 方法将值显示为字符串,而不是从数组值中显示.
words.join(' '); // I JavaScript am learning
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4