按字母顺序对字符串数组进行排序 [英] Sort an array of strings alphabetically

查看:69
本文介绍了按字母顺序对字符串数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到每个字符串的情况,我需要对字母数组进行排序,更具体一点,我想先写大写字母,我该怎么做?我找到了一个处理这个的解决方案,但有一个我不知道如何解决的错误:

  var  arr = [  T  h  e  c < span class =code-string> a,  t  s  a  t  o  n  t  h  e  m   a  t]; 
arr.sort( function (a,b)
{
var x = a.toLowerCase(),y = b.toLowerCase();

if (x< y){ return -1}
else if (x> y){返回 1 }
else { return 0 };
}); // - > [a,a,a,c,e,e,h,h,m,n,o,s, t,T,t,t,t]



为什么首都在名单上排名第一T的意思是这样的:

 [a,a,a,c,e,e, h,h,m,n,o,s,T,t,t,t,t] 



PS我很抱歉以前令人困惑的问题。我正在尝试根据案例对数组进行排序。



我尝试了什么:



。排序( function (a,b){
return a.toLowerCase()。localeCompare(b.toLowerCase());
});



输出相同

解决方案

Quote:

为什么大写T不会先行?

它不会先走,因为你这样问。

很难想到这段代码是你的! 3行,你不明白代码。



这是功课,所以你必须找到自己的错误。

建议:阅读代码,问题应该是显而易见的。如果您不理解某些内容,请搜索定义和用法。


首先要了解自己:

1. JavaScript String toLowerCase()方法 [ ^ ]吗?

2. Ascii表 - ASCII字符代码和html,八进制,十六进制和十进制图表转换 [ ^ ]

然后仔细研究 JavaScript Array sort()方法 [ ^ ]


I would need to sort an array of letters considering the case of each string, to be more specific, I want upper case letters to go first, how can I do this? I found a solution that handles this but there is one bug that I don`t know how to fix:

var arr = ["T", "h", "e", "c", "a", "t", "s", "a", "t", "o", "n", "t", "h", "e", "m", "a", "t"];
arr.sort(function(a, b)
{
    var x = a.toLowerCase(), y = b.toLowerCase();
    
    if(x < y) {return -1}
    else if (x > y ) {return 1} 
    else {return 0};
}); //-> ["a", "a", "a", "c", "e", "e", "h", "h", "m", "n", "o", "s", "t", "T", "t", "t", "t"]


Why won`t the capital t be first on the list of 'T'`s, like this :

["a", "a", "a", "c", "e", "e", "h", "h", "m", "n", "o", "s",  "T", "t", "t", "t", "t"]


P.S I am sorry for previous confusing question. I am trying to sort an array according to the case.

What I have tried:

.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});


The output is the same

解决方案

Quote:

Why capital T doesn't go first?

It don't go first because you asked it this way.
It is hard to think this code is yours! 3 lines and you don't understand the code.

This is homework, so you have to find yourself what is wrong.
Advice: read the code, the problem should be obvious. If you don't understand something, search for definition and usage.


Help yourself by first understand:
1. What does JavaScript String toLowerCase() Method[^] do?
2. Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion[^]
Then study carefully JavaScript Array sort() Method[^]


这篇关于按字母顺序对字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆