Home > Web Front-end > JS Tutorial > Usage of sort() method in JS_Basic knowledge

Usage of sort() method in JS_Basic knowledge

WBOY
Release: 2016-05-16 19:24:47
Original
1280 people have browsed it

Returns an Array object whose elements have been sorted.

arrayobj.sort(sortfunction)
Parameters
arrayObj
Required. Any Array object.
sortFunction
Optional. is the name of the function used to determine the order of elements. If this parameter is omitted,
then the elements will be sorted in ascending ASCII character order.
Description
The sort method sorts Array objects appropriately;
No new Array objects are created during execution.

If a function is provided for the sortfunction argument, the function must return one of the following values:

A negative value if the first argument passed is smaller than the second argument.
Zero if the two arguments are equal.
Positive value, if the first parameter is larger than the second parameter.
Demo1 (default alphabetical order):

Copy code The code is as follows:
< ;script language="javascript">
var nameArr = new Array("douguoqiang","hedan","redhacker","panliu888","maxuan","xuejianping","lanse","zhangsan", "lisi","wangwu");
nameArr.sort();
for (var i = 0; i < nameArr.length; i ) {
document.writeln(nameArr[i]) ; With parameters):




Copy code

The code is as follows:
<script> <a style="CURSOR: pointer" data="83313" class="copybut" id="copybut83313" onclick="doCopy('code83313')"> var numArr = new Array(12,23,1,4,23,34,2,5); <u> numArr.sort(function compare(a,b){return a-b;}); </u> for (var i = 0; i<numArr.length; i ) { </a> document.write(numArr[i] "<br>"); } </a> </div></script>

Results:
1
2
4
5
12
23
23
34


Demo3 (Demo3 reverse sorting ):





Copy code

The code is as follows:
<script> <a style="CURSOR: pointer" data="61287" class="copybut" id="copybut61287" onclick="doCopy('code61287')"> var numArr = new Array(12,23,1,4,23,34,2,5); <u> numArr.sort(function compare(a,b){return b-a;}); </u> for (var i = 0; i<numArr.length; i ) { </a> document.write(numArr[i] "<br>"); </a></span> } </div></script>

Result:
34
23
23
12
5
4
2
1


Demo4 (the second version of Demo3 Writing method):





Copy code

The code is as follows:
<script> <a style="CURSOR: pointer" data="808" class="copybut" id="copybut808" onclick="doCopy('code808')"> var numArr = new Array(12,23,1,4,23,34,2,5); <u> numArr.sort(new Function("a","b","return a-b;")); </u> for (var i = 0; i<numArr.length; i ) { </a> document.write(numArr[i] "<br>"); </a></span> } </div></script>

Results:
1
2
4
5
12
23
23
34


Demo5 (The third way of writing Demo3):





Copy code

The code is as follows:
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template