# 数组类总结

1.数组随机取值：
var arr = [3,5,7,89,436,789,980];
arr[Math.floor(Math.random()*arr.length)];

2.数组打乱顺序：

function randomsort(a, b) {
return Math.random()>.5 ? -1 : 1;
//用Math.random()函数生成0~1之间的随机数与0.5比较，返回-1或1
}

function shuffle(array) {
var iLength = array.length,
i = iLength,
nTemp,
iRandom;
while ( i-- ) {
if (i !== (iRandom = Math.floor(Math.random()*iLength))) { // 不是同一个数组项的前提下进行互换
nTemp = array[i];
array[i] = array[iRandom];
array[iRandom] = nTemp;
};
};
return array;
}
console.log(shuffle([1,2,3,4,5,6,7,8]));
ES6的写法：
Array.prototype.shuffle = function() {
let m = this.length, i;
while (m) {
i = (Math.random() * m--) >>> 0;
[this[m], this[i]] = [this[i], this[m]];
}
return this;
}

[1, 2, 3, 4, 5, 6, 7].shuffle();

3.数组排序：

function asc(a,b) {
return a < b ? -1 : 1;//如果a小于b不交换，否则交换，即升序排列
}
var arr = [4,56,789,2,5898,78,90];

arr.sort(asc);//[2, 4, 56, 78, 90, 789, 5898]

function desc(a,b) {
return a > b ? -1 : 1;;//如果a大于b不交换，否则交换，即将序排列
}
var arr = [4,56,789,2,5898,78,90];

arr.sort(desc);//[5898, 789, 90, 78, 56, 4, 2]

var arr = [6,2,4,3,5,1];
arr.sort( function(x, y) {
if (x % 2 ==0) return 1;
if (x % 2 !=0) return -1;
});
console.log(arr);//[3, 5, 1, 4, 2, 6]

4.数组去重：

function unique(arr){
var obj = {},
tmp = [];
for(var i = 0 ;i< arr.length;i++){
if( !obj[arr[i]] ){
obj[arr[i]] = 1;
tmp.push(arr[i]);
}
}
return tmp;
}

console.log(unique([2,3,4,4,5,2,3,6]));//[2, 3, 4, 5, 6]

function unique(arr){
var tmp = [];
for(var i = 0;i< arr.length;i++){
if(tmp.indexOf(arr[i]) < 0){
tmp.push(arr[i]);
}
}
return tmp;
}
console.log(unique([2,3,4,4,5,2,3,6]));//[2, 3, 4, 5, 6]