位置: 编程技术 - 正文
推荐整理分享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接受一个自定义的比较函数,如下例:
排序完我们又有个疑问,如何控制升序和降序呢?
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操作
标签: js数组排序方法sort
本文链接地址:https://www.jiuchutong.com/biancheng/385643.html 转载请保留说明!友情链接: 武汉网站建设