array.splice(a,b) 从array[a]开始删除b个元素
1.字符串排序
var m = ['aa', 'bb', 2, 3, 7, 9];
m.sort(function (a, b) {
if (a == b){
return 0;
}
if (typeof a ===typeof b) {
return a < b ? -1 : 1; //-1不需要重新排序 1需要调换位置
}
return typeof a < typeof b ? -1 : 1;
})
console.log(m); //[ 2, 3, 7, 9, 'aa', 'bb' ]
2.对对象进行排序
let s = [
{ first: 'B', last: 'A' },
{first:'A',last:'C'}
]
let by = function (name, minor) {
return function (o, p) {
let a, b;
if (o && p && typeof o === 'object' && typeof p === 'object') {
a = o[name];
b = p[name];
if (a == b) {
return typeof minor === 'function' ? minor(o, p) : 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
} else {
throw {
name: 'Error',
message: 'Expected an object when sorting by' + name
};
}
};
};
console.log(s.sort(by('last'),by('first')));
3.遍历数组方法速度排序
for > for-of > forEach > filter > map > for-in







网友评论