sort(),sort(function(a,b){return a-b;})之间的区别;和排序(函数(a,b){...}) [英] Difference between sort(), sort(function(a,b){return a-b;}); and sort(function(a,b){...})
问题描述
我正在尝试理解sort()的工作方式以及我应该如何使用它。
I am trying to understand how exactly sort() works and how I am supposed to use it.
我做了一些研究(谷歌)并经历了类似的关于stackoverflow的问题,但仍有一些事情不是100%清楚的。
I did some research (google) and went through the similar questions here on stackoverflow, but there are still a few things not 100% clear to me.
所以到目前为止我的理解如下:
So my understanding so far is the following:
有:
没有参数的sort():只对 String的简单数组进行排序值按字母顺序以及升序顺序
例如
// sort alphabetically and ascending:
var myArr=["Bob", "Bully", "Amy"]
myArr.sort() // Array now becomes ["Amy", "Bob", "Bully"]
使用函数作为参数的sort():根据数组属性对数组中的对象进行排序;但是,这些项目会比较为数字
sort() with a function as a parameter: sorts objects in arrays according to their properties; the items are, however, compared as numbers
myArr.sort(function(a,b) {
return a - b;
});
使用函数作为参数的sort():根据数组属性对数组中的对象进行排序;这些项目可以是数字或字符串
sort() with a function as a parameter: sorts objects in arrays according to their properties; the items can be numbers or Strings
myArr.sort(function(a, b) {
if (a.sortnumber < b.sortnumber) return -1;
else if (a.sortnumber > b.sortnumber) return 1;
return 0;
});
我尝试使用所有这3个sort()函数对以下数组进行排序。
I tried sorting the following array with all these 3 sort() functions.
var myArr = [{
"sortnumber": 9,
"name": "Bob"
},
{
"sortnumber": 5,
"name": "Alice"
},
{
"sortnumber": 4,
"name": "John"
},
{
"sortnumber": 3,
"name": "James"
},
{
"sortnumber": 7,
"name": "Peter"
},
{
"sortnumber": 6,
"name": "Doug"
},
{
"sortnumber": 2,
"name": "Stacey"
}];
//myArr.sort(); // doesn't do anything since it doesn't know on what property to sort
/*
myArr.sort(function(a, b) {
return (a.sortnumber - b.sortnumber); // sorts array
return (a.name - b.name); // doesn't sort array
});
*/
/*
// sorts array even when I use name as property to sort on
myArr.sort(function(a, b) {
if (a.sortnumber < b.sortnumber) return -1;
else if (a.sortnumber > b.sortnumber) return 1;
return 0;
});
*/
console.log(myArr);
这里也是一个小提琴。
所以,我的问题是:
- 我的理解是否正确?
- 我有什么遗漏吗?
- 如果第三种情况一直有效,我可以吗?总是坚持它或者是
其他两种情况在某些方面更有效率或对
第三种情况有任何好处?
如果有人能详细说明,我会非常感激以上。谢谢。
I would really appreciate it if anyone could elaborate on the above. Thank you.
推荐答案
好的,经过一些额外的研究后,请浏览 MDN文档,以及 arraysort 和 arraysort2 链接,我发现非常有帮助,我创建了一个可能对其他人有用的幻灯片,所以我在这里发布它。谢谢大家的答案!
Ok, so after some additional research, going through the MDN documentation, and the arraysort and arraysort2 links, which I found very helpful, I created a slide that could probably be of use to someone else, so I am posting it here. Thank you all for your answers!
< img src =https://i.stack.imgur.com/81miP.pngalt =在此处输入图像说明>
这篇关于sort(),sort(function(a,b){return a-b;})之间的区别;和排序(函数(a,b){...})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!