js_数组排序
使用sort方法排序。
① 数字排序
var arr9 = [3,4,2,8,1,3];
document.write(“
“+arr9);
arr9.sort();
document.write(“
“+arr9);
② 字串排序
var arr = new Array()
arr[0] = “George”
arr[1] = “John”
arr[2] = “Thomas”
arr[3] = “James”
arr[4] = “Adrew”
arr[5] = “Martin”
document.write(arr + “
“);
document.write(arr.sort());
③ 自定义排序
// 按数字大小排序
function sortNumber(a,b)
{
return a - b;
}
var arr10 = new Array(6);
arr10[0] = “10”;
arr10[1] = “5”;
arr10[2] = “40”;
arr10[3] = “25”;
arr10[4] = “1000”;
arr10[5] = “1”;
document.write(arr10);
document.write(“
“);
document.write(arr10.sort());// 按字符大小排序
document.write(“
“);
document.write(arr10.sort(sortNumber));// 按数字大小排序
④ 降序排序
// 降序
function sortdes(a,b){
if (a > b){
return -1;
}
else{
return 1;
}
}
var arr = new Array();
arr[0] = “George”;
arr[1] = “John”;
arr[2] = “Thomas”;
arr[3] = “James”;
arr[4] = “Adrew”;
arr[5] = “Martin”;
document.write(arr + “
“);
document.write(arr.sort());// 字串升序
document.write(“
“);
document.write(arr.sort(sortdes));// 字串降序
⑤ 对象排序
var json1 = {username:”gary”,age:30};
var json2 = {username:”keke”,age:34};
var json3 = {username:”arry”,age:25};
var arr10 = [];
arr10.push(json1);
arr10.push(json2);
arr10.push(json3);
document.write(“
arr10:”+JSON.stringify(arr10));
arr10.sort(function(a,b){
return a.age - b.age;// 按年龄从小到大排序
});
document.write(“
arr10:”+JSON.stringify(arr10));
还没有评论,来说两句吧...