Nodejs工具函数集

对数组中的对象进行排序

函数:

1
2
3
4
5
function keysort (key, desc) {
return function (a, b) {
return desc ? (a[key] < b[key]) : (a[key] > b[key]);
};
}

示例:

1
2
const arr = [{"id":2,"name":"2"},{"id":1,"name":"1"}]
arr.sort(keysort('name', 'desc'));

判断是否是Float浮点

1
2
3
function isFloat (num) {
return num !== parseInt(num);
}

保留两位小数,同时不四舍五入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// number
// num 保留位数
function toFixedNum (number, num) {
const type = typeof (number);
let number_arr = [];
if (type === 'number') {
const str = number.toString();
number_arr = str.split('.');
} else if (type === 'string') {
number_arr = number.split('.');
}
if (number_arr.length > 1) {
number = number_arr[0] + '.' + number_arr[1].substr(0, num);
}
return parseFloat(number);
}

给出开始时间和结束时间,算出中间所有的日期

1
2
3
4
5
6
7
8
9
10
11
12
13
// start : 2018-01-01
// end : 2018-01-03
// return : ["2018-01-01","2018-01-02","2018-01-03"]
function getDate (start, end) {
start = new Date(start).getTime();
end = new Date(end).getTime();
const date = [];
for (; start <= end; start += 86400000) {
const tmp = new Date(start);
date.push(tmp.getFullYear() + '-' + (tmp.getMonth() + 1) + '-' + tmp.getDate());
}
return date;
}
我就想试试,没别的意思!