js的封装函数功能:数组操作
// arrayEqual
// 判断两个数组是否相等
function arrayEqual(arr1, arr2) {
if (arr1 === arr2) return true;
if (arr1.length != arr2.length) return false;
for (var i = 0; i < arr1.length; ++i) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
}
//获取对象数组某些项
//获取对象数组某些项
//var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//getOptionArray(arr,'a,c')
//[{a:1,c:9},{a:2,c:5},{a:5,c:underfind},{a:4,c:5},{a:4,c:7}]
//只获取某一项的值
//getOptionArray(arr,'a',1)
//getOptionArray(arr,'b',1)
//[2, 3, 9, 2, 5]
function getOptionArray(arr, keys, type) {
var newArr = [];
if (!keys) {
return arr
}
//是否只是需要获取某一项的值
if (type === 1) {
for (var i = 0, len = arr.length; i < len; i++) {
newArr.push(arr[i][keys])
}
return newArr;
}
var _keys = keys.split(','), newArrOne = {};
for (var i = 0, len = arr.length; i < len; i++) {
newArrOne = {};
for (var j = 0, len1 = _keys.length; j < len1; j++) {
newArrOne[_keys[j]] = arr[i][_keys[j]]
}
newArr.push(newArrOne);
}
return newArr;
}
//排除数组某些项
//排除数组某些项
//var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//filterOptionArray(arr,'a')
//[{b:2,c:9},{b:3,c:5},{b:9},{b:2,c:5},{b:5,c:7}]
//filterOptionArray(arr,'a,c')
//[{b:2},{b:3},{b:9},{b:2},{b:5}]
function filterOptionArray(arr, keys) {
var newArr = [];
var _keys = keys.split(','), newArrOne = {};
for (var i = 0, len = arr.length; i < len; i++) {
newArrOne = {};
for (var key in arr[i]) {
//如果key不存在排除keys里面,添加数据
if (_keys.indexOf(key) === -1) {
newArrOne[key] = arr[i][key];
}
}
newArr.push(newArrOne);
}
return newArr;
}
//对象数组排序
//对象数组的排序
//var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//arraySort(arr2,'a,b') a是第一排序条件,b是第二排序条件
//[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:4,b:2,c:5},{a:4,b:5,c:7},{a:5,b:9}]
function arraySort (arr, sortText) {
if (!sortText) {
return arr;
}
var _sortText = sortText.split(',').reverse(), _arr = arr.slice(0);
for (var i = 0, len = _sortText.length; i < len; i++) {
_arr.sort(function (n1, n2) {
return n1[_sortText[i]] - n2[_sortText[i]];
})
}
return _arr;
}