一、sort(orderfunction):按指定的參數對數組進行排序,默認以字符串的字典順序進行排序(若是是數字,會先轉成字符),若是都是數字,則按數字第一位大小排序,如:html
var arr=[10,-2,4,1,8,15,8,49,27,6],b=arr.sort();console.log(b); [-2, 1, 10, 15, 27, 4, 49, 6, 8, 8] undefined
添加orderfunction,可排序純數字數組,以下:數組
1 unction sortnumber(a,b){return a-b} 2 3 var arr=[10,-2,4,1,8,15,8,49,27,6], 4 5 b=arr.sort(sortnumber);console.log(b); 6 7 [-2, 1, 4, 6, 8, 8, 10, 15, 27, 49] 8 undefined
sort()的返回值和原值都是排序過的值,檢驗以下:函數
1 function sortnumber(a,b){return a-b} 2 var arr=[10,-2,4,1,8,15,8,49,27,6], 3 b=arr.sort(sortnumber);console.log(arr); 4 5 [-2, 1, 4, 6, 8, 8, 10, 15, 27, 49] 6 undefined 7 8 9 function sortnumber(a,b){return a-b} 10 var arr=[10,-2,4,1,8,15,8,49,27,6] 11 ,b=arr.sort(sortnumber);console.log(arr==b); 12 13 true 14 undefined
對對象數組進行排序,能夠用如下函數:測試
/by函數接受一個成員名字符串作爲參數 //並返回一個能夠用來對包含該成員的對象數組進行排序的比較函數 var by = function(name){ return function(o, p){ var a, b; if (typeof o === "object" && typeof p === "object" && o&& p) { a = o[name]; b = p[name]; if (a === b) { return 0; } if (typeof a === typeof b) { return a < b ? -1 : 1; } return typeof a < typeof b ? -1 : 1; } else { throw ("error"); } } }
調用by函數能夠這樣寫:spa
var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
直接調用函數:
employees.sort(by("age"));
二、slice(start,end)英文名爲「切片」 表示從數組中切去某一片斷,start爲開始索引,end爲終止索引位置(切出來的部分包括start,不包括end),原數組不變code
1 var arr=[10,-2,4,1,8,15,8,49,27,6], 2 b=arr.slice(3,6);console.log(arr==b); 3 4 false 5 undefined 6 7 var arr=[10,-2,4,1,8,15,8,49,27,6], 8 b=arr.slice(3,6);console.log(b); 9 10 [1, 8, 15] 11 undefined 12 13 var arr=[10,-2,4,1,8,15,8,49,27,6], 14 b=arr.slice(3,6);console.log(arr); 15 16 [10, -2, 4, 1, 8, 15, 8, 49, 27, 6] 17 undefined
另外,start=end時,切出來爲空數組b= [];start爲負數時,切出來也爲空數組b=[];htm
當start爲正數時,end爲負數時,-1表示數組表示最後一個(切片是end爲最後一個,左閉右開,不切出來),-2表示倒數第二個,這時,取不到最後一個數字,以此類推,測試以下:對象
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(3,3);console.log(b);
[]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(3,-1);console.log(b);
[1, 8, 15, 8, 49, 27]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(-1,2);console.log(b);
[]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(-1,5);console.log(b);
[]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(-1,5);console.log(arr);
[10, -2, 4, 1, 8, 15, 8, 49, 27, 6]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(3,0);console.log(b);
[]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(3,-2);console.log(b);
[1, 8, 15, 8, 49]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(3,-0);console.log(b);
[]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(3,-1);console.log(b);
[1, 8, 15, 8, 49, 27]
undefined
var arr=[10,-2,4,1,8,15,8,49,27,6],
b=arr.slice(3,11);console.log(b);
[1, 8, 15, 8, 49, 27, 6]
undefined