JavaScript常用工具类util记录,时不时更新
var toUrls = function (o) {
var arr = [];
for (var p in o) {
if (o.hasOwnProperty(p)) {
arr.push(encodeURIComponent(p) + "=" + encodeURIComponent(o[p]));
}
}
return '?' + arr.join("&");
}
export const accurateCalc = (arg1 = 0, arg2 = 0, type = 'add') => {
let result = 0;
const space1 = arg1.toString().split('.')[1] || 0;
const space2 = arg2.toString().split('.')[1] || 0;
const maxSpace = Math.max(space1.length || 0, space2.length || 0);
const multiple = Math.pow(10, maxSpace);
if (type === 'add') {
result = Math.round(arg1 * multiple + arg2 * multiple) / multiple;
} else if (type === 'sub') {
result = Math.round(arg1 * multiple - arg2 * multiple) / multiple;
}
return result;
}
export const handleCount = (num, count) => {
return count ? accurateCalc(num, count, 'sub') : accurateCalc(num, Math.abs(count));
}
export const toParseNum = (num = 0) => {
const str = num.toString().split('.');
return str[1] ? (+str[0]) + 1 : num;
}
export const toTargetNum = (num = 0) => {
const str = num.toString().split('.');
let str1 = str[1] != undefined ? str[1] : '';
if (str1.length > 4) str1 = +str1.slice(0, 4) + 1;
return str1 ? +(`${str[0]}.${str1}`) : num;
}
export const handleWeeks = (m) => {
const totalDay = moment(m).daysInMonth();
const allMonthData = [];
for (let i = 0; i < totalDay; i++) {
const d = i + 1;
const o = `${m}${d < 10 ? `0${d}` : d}`
allMonthData.push(o)
}
let firstDayWeek = moment(allMonthData[0]).weekday();
const weeks = [];
function getWeek(days, length) {
let newWeek = days.splice(0, length);
weeks.push(newWeek);
days.length > 7 ? getWeek(days, 7) : weeks.push(days);
}
getWeek(allMonthData, 7 - firstDayWeek);
return weeks;
}
export const numEnum = ["一", "二", "三", "四", "五", "六"];