// 数组对象排序方法
compare(property) {
return function (a, b) {
const value1 = a[property]
const value2 = b[property]
return value2 - value1 // 正序 return value1 - value2 降序
}
},
let arr = [ {name: '小明', age: 18},
{name: '小花', age: 20}]
比较两个人的年龄大小:
let newArr = arr.sort(this.compare('age'))
console.log(newArr)
计算两个人的年龄之和:
let sumCount = arr.reduce((ageSum, currStudent) => {
return ageSum + Number(currStudent.age);
}, 0)
console.log(sumCount)
其它相关校验方法:
// 保留几位小数,不够位数自动补齐 (num代表要处理的数值,floatNum代表保留小数位数)
keepTwoDecimalFull(num, floatNum) {
let result = parseFloat(num);
if (isNaN(result)) {
console.log('传递参数错误,请检查!');
return false;
}
result = Math.round(num * (floatNum == 2 ? 100 : 10000)) / (floatNum == 2 ? 100 : 10000);
let s_x = result.toString(); //将数字转换为字符串
let pos_decimal = s_x.indexOf('.'); //小数点的索引值
// 当整数时,pos_decimal=-1 自动补0
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
}
// 当数字的长度< 小数点索引+2时,补0
while (s_x.length <= pos_decimal + floatNum) {
s_x += '0';
}
return s_x;
}
console.log(this.keepTwoDecimalFull(2.565, 2))
// 获取某个日期是第多少周 (val代表某个日期)
getWeekNumber(val) {
const year = val.getFullYear() //获取年
const month = val.getMonth() + 1 //获取月
const day = val.getDate() //获取天
const isLeapYear = (year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0) //判断是否为闰年
const second = isLeapYear ? 29 : 28
const monthList = [31, second, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].splice(0, month - 1) //获取月份数组
let currentDays; //当前日期天数
let currentWeek; //当前周数
//计算天数
currentDays = month === 1 ? day : (monthList.reduce((t, v) => {
return t + v
}, 0)) + day
//计算是第几周
currentWeek = currentDays % 7 === 0 ? currentDays / 7 : Math.ceil(currentDays / 7)
return currentWeek
}
console.log(this.getWeekNumber(new Date('2023-01-01'))