简体   繁体   English

比较两个字符串的JavaScript

[英]Compare two strings javascript

Compare the given strings and display the string that comes alphabetically first. 比较给定的字符串,并显示按字母顺序排在最前面的字符串。 Need help with this question, anything I try ends up wrong. 在这个问题上需要帮助,我尝试的任何事情都会出错。

var personName1 = "Ann"; // Code will be tested with different names
var personName2 = "Anthony";

You're looking for the sort feature. 您正在寻找排序功能。

Throw the items into an array, sort them, and return the first result. 将项目放入数组,对它们进行排序,然后返回第一个结果。

 var names = ['Bob', 'James', 'Billy']; console.log (names.sort()[0]) 

Basically you are storing the variables or names in an array and sorting it, when you sort it you will get an array returned and you are fetching it by index zero. 基本上,您是将变量或名称存储在数组中并对其进行排序,对它进行排序时,您将得到一个返回的数组,并通过索引零来获取它。

[personName1, personName2].sort()[0]

This is smaller code version of mdawsondev's answer. 这是mdawsondev答案的较小代码版本。

Add those variable reference to an array after which you can use sort & localCompare method to get the sorted array 将这些变量引用添加到数组后,可以使用sortlocalCompare方法获取排序后的数组

 var personName1 = "Ann"; var personName2 = "Anthony"; var items = [personName1, personName2]; items.sort((a, b) => a.localeCompare(b)); console.log(items) 

The basic thing you need to do is add the two variables you have provided in an array and apply the sort function on them. 您需要做的基本事情是将数组中提供的两个变量相加,然后对它们应用sort函数。 The sort function will sort the arry in your case in lexicographical order. 排序功能将按照字典顺序对您的案件进行排序。 After sorting the array the first element will return the alphabetically first element. 对数组进行排序后,第一个元素将返回按字母顺序排列的第一个元素。 The Code- 编码-

[personName1, personName2].sort()[0] Hope it helps. [personName1, personName2].sort()[0]希望对您[personName1, personName2].sort()[0]帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM