JS --------reduce()函数求和 (累加器)
语法:array.reduce(function(previousVal, currentValue, currentIndex, arr), initialValue)
reduce函数为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接收四个参数(或者上一次回调函数的返回值),当前元素值、当前索引值、调用reduce的数组。(对空数组不执行回调函数)
callback(执行数组中每个值得函数,包含四个参数)
1、previousVal 初始值 (必须)
2、currentValue 数组当前被处理的元素 (必须)
3、index 索引 (可选)
4、array 调用reduce的数组 (可选)
一、计算求和
let arr = [1,2,3,4,5]
let res = arr.reduce(function(prev,cur,index,arr){
return prev + cur
},0) // =>0 即initialValue 这里设置初始值 防止arr = [ ] 时报错
简单算法:
let arr = [1,2,3,4]
let sum = arr.reduce((x,y) => x+y)
let mul = arr.reduce((x,y) => x*y)
console.log(sum) // 10
console.log(mul) // 24
二、计算数组中每个元素出现得次数
let names = [ ' Alice' , 'Bob' , 'Tiff' , 'Json' , 'Alice' ]
let nameNum = names.reduce((pre , cur)=>{
if(cur in pre ){
pre[cur]++
}else{
pre[cur] = 1
}
return pre
},{})
console.log(nameNum) // {Ailce: 2 , Bob: 1 , Tiff:1 , Json:1}
三、数组去重
let arr = [1,2,1,3,4,5,6,7,5]
let newArr = arr.reduce((pre , cur )=>{
if(!pre.includes(cur)){
return pre.concat(cur)
}else{
return pre
}
},[ ])
console.log(newArr) // [ 1,2,,3,4,5,6,7 ]
四、对象属性求和
let result = [
{
id: 0,
subject: 'math',
score: 20
},
{
id: 1,
subject: 'chinese',
score: 40
},
{
id: 2,
subject: 'english',
score: 60
},
]
let sum = result.reduce(function(prev, cur){
return cur.score + prev
}, 0)
console.log(sum) // 120
之外======= 获取对象的key 和 value
本次以时间对象为参考
let rate = data.rateDetail // data.rateDetail: { 2022-03-18: 188 }
console.log(rate)
// 分别获取对象的key和value
let data_key = []
let data_value = []
for (let i in rate) {
data_key.push(i)
data_value.push(rate[i])
}
//将数组合并成对象
let times = data_key
let timesDesc = data_value
let option = []
const f1 = (key, arr) => arr.map(item => ({
[key]: item
}))
const getMaxArr = (times, timesDesc) => (times.length >= timesDesc.length) ? times : timesDesc
const mergeArr = (oldArr, arr) => oldArr.map((item, index) => ({
item,
...arr[index]
}))
// let list1 = f1('times', times)
let list2 = f1('timesDesc', timesDesc)
//将时间进行排序
times.sort(function(a, b) {
let obj1 = a
let obj2 = b
const times1 = Math.floor(new Date(obj1).getTime() / 1000)
const times2 = Math.floor(new Date(obj2).getTime() / 1000)
return times1 - times2
})
let options = mergeArr(getMaxArr(times, timesDesc), list2)
console.log(options) //[ {item: "2022-03-18" , timesDesc: 188} ]
获取当前时间
getCurrentTime() {
//获取当前时间并打印
let that = this
let yy = new Date().getFullYear()
let mm = new Date().getMonth() + 1
let dd = new Date().getDate()
let hh = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
//that.gettime = yy+'/'+mm+'/'+dd+' '+hh+':'+mf+':'+ss
that.times = hh + ':' + mf + ':' + ss
}
获取下一天时间
getNextDay(dates, day) {
let date = new Date(dates)
date.setDate(date.getDate() + day)
let y = date.getFullYear()
let m = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
let d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
return y + "-" + m + "-" + d
}
时间格式处理
datetimeparse(timestamp, format, prefix) {
if (typeof timestamp == 'string') {
timestamp = Number(timestamp)
}
//转换时区
let currentZoneTime = new Date(timestamp)
let currentTimestamp = currentZoneTime.getTime()
let offsetZone = currentZoneTime.getTimezoneOffset() / 60 //如果offsetZone>0是西区,西区晚
let offset = null
//客户端时间与服务器时间保持一致,固定北京时间东八区。
offset = offsetZone + 8
currentTimestamp = currentTimestamp + offset * 3600 * 1000
let newtimestamp = null
if (currentTimestamp) {
if (currentTimestamp.toString().length === 13) {
newtimestamp = currentTimestamp.toString()
} else if (currentTimestamp.toString().length === 10) {
newtimestamp = currentTimestamp + '000'
} else {
newtimestamp = null
}
} else {
newtimestamp = null
}
let dateobj = newtimestamp ? new Date(parseInt(newtimestamp)) : new Date()
let YYYY = dateobj.getFullYear()
let MM = dateobj.getMonth() > 8 ? dateobj.getMonth() + 1 : '0' + (dateobj.getMonth() + 1)
let DD = dateobj.getDate() > 9 ? dateobj.getDate() : '0' + dateobj.getDate()
let HH = dateobj.getHours() > 9 ? dateobj.getHours() : '0' + dateobj.getHours()
let mm = dateobj.getMinutes() > 9 ? dateobj.getMinutes() : '0' + dateobj.getMinutes()
let ss = dateobj.getSeconds() > 9 ? dateobj.getSeconds() : '0' + dateobj.getSeconds()
let output = ''
let separator = '/'
if (format) {
separator = format.match(/-/) ? '-' : '/'
output += format.match(/yy/i) ? YYYY : ''
output += format.match(/MM/) ? (output.length ? separator : '') + MM : ''
output += format.match(/dd/i) ? (output.length ? separator : '') + DD : ''
output += format.match(/hh/i) ? (output.length ? ' ' : '') + HH : ''
output += format.match(/mm/) ? (output.length ? ':' : '') + mm : ''
output += format.match(/ss/i) ? (output.length ? ':' : '') + ss : ''
} else {
output += YYYY + separator + MM + separator + DD
}
output = prefix ? (prefix + output) : output
return newtimestamp ? output : ''
}
计算天数
getAll(begin, end) {
let arr1 = begin.split("-") //这里可以换成/ 就2020/01/01 这种
let arr2 = end.split("-")
let arr1_ = new Date()
let arrTime = []
arr1_.setUTCFullYear(arr1[0], arr1[1] - 1, arr1[2])
let arr2_ = new Date();
arr2_.setUTCFullYear(arr2[0], arr2[1] - 1, arr2[2])
let unixDb = arr1_.getTime()
let unixDe = arr2_.getTime()
for (let k = unixDb; k <= unixDe;) {
arrTime.push(this.datetimeparse(k, 'YY-MM-DD')) // 此处调用时间格式处理方法 datetimeparse()
k = k + 24 * 60 * 60 * 1000
}
return arrTime
}