示例: 按字母顺序对单词进行排序
// 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 之前打印?
这是因为
JavaScript 的
I 和
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