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。但是,amIJavaScript 之后打印。

为什么 I 和 JavaScript 会在 am 之前打印?

这是因为 IJavaScript 中的 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

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战