位置: 编程技术 - 正文

Javascript 数组排序详解(js数组排序方法sort)

编辑:rootadmin

推荐整理分享Javascript 数组排序详解(js数组排序方法sort),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:js数组排序方法sort,js数组排序方法sort,js数组排列组合,javascript数组排序输出,js数组排列组合,JavaScript 数组排序,javascript数组排序函数,javascript数组排序方法,内容如对您有帮助,希望把文章链接给更多的朋友!

如果你接触javascript有一段时间了,你肯定知道数组排序函数sort,sort是array原型中的一个方法,即array.prototype.sort(),sort(compareFunction),其中compareFunction是一个比较函数,下面我们看看来自Mozilla MDN 的一段描述:If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic (“dictionary” or “telephone book,” not numerical) order. For example, “″ comes before “9″ in lexicographic order, but in a numeric sort 9 comes before .

下面看些简单的例子:

从上例可以看出,默认是按字典中字母的顺序来排序的。

幸运的是,sort接受一个自定义的比较函数,如下例:

排序完我们又有个疑问,如何控制升序和降序呢?

Javascript 数组排序详解(js数组排序方法sort)

comparFunction的排序规则是这样的:1.If it returns a negative number, a will be sorted to a lower index in the array.2.If it returns a positive number, a will be sorted to a higher index.3.And if it returns 0 no sorting is necessary.

下面我们来看看摘自Mozilla MDN上的一段话:The behavior of the sort method changed between JavaScript 1.1 and JavaScript 1.2.为了解释这段描述,我们来看个例子:

In JavaScript 1.1, on some platforms, the sort method does not work. This method works on all platforms for JavaScript 1.2.

In JavaScript 1.2, this method no longer converts undefined elements to null; instead it sorts them to the high end of the array.详情请戳这里。

希望本文对你学习和了解sort()方法有帮助,文中不妥之处还望批评斧正。

参考链接:

javascript数组详解 如果你是一个有经验的开发者,你可能会认为这个问题比较简单,但是有的时候,我们会感觉这个问题比较有趣。首先我们来看看数组的定义:Anarrayisju

Javascript中Array.prototype.map()详解 在我们日常开发中,操作和转换数组是一件很常见的操作,下面我们来看一个实例:vardesColors=[],srcColors=[{r:,g:,b:},//White{r:,g:,b:},//Gray{r:0,g:0,

Javascript 构造函数详解 一、什么是构造函数在一些面向对象的语言,如Java、C++、PHP中,构造函数是很常见的。在Javascript中构造函数首先是一个普通的函数,它可以使用new操作

本文链接地址:https://www.jiuchutong.com/biancheng/385643.html 转载请保留说明!

上一篇:Javascript中的默认参数详解(javascript 默认参数)

下一篇:javascript数组详解(javascript数组操作方法)

免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络