示例:按字母顺序排序单词
// 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 循环来迭代数组元素并显示它们。
在这里,我们是按字母顺序排序的。所以,预期的输出是 am、I、JavaScript 和 learning。但是,am 在 I 和 JavaScript 之后打印。
为什么 I 和 JavaScript 会在 am 之前打印?
这是因为 I 和 JavaScript 中的 J 是大写字母。而且,当我们使用 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
另请阅读