【数组的reduce方法】:(note)
- 1.reduce方法接收一个函数作为累加器(“连续操作器”)。
- 2.数组中的每个值(从左到右)开始合并(不一定是相加!),最终为一个值。
- 3.reduce为数组中的每一个元素【依次执行】回调函数,但不包括数组中被删除或从未被赋值的元素。
- 4.reduce方法最终返回的是最后一次调用累加器的结果。
- 5.累加器函数接受四个参数:preValue, nowValue, nowIndex, arr
-
--preValue:
-
--第一次调用时是初始值,如果初始值没有指定,就是数组中第一个元素的值,同时nowValue变为数组中的第二个值。
-
--以后调用时是上一次该回调函数的返回值;
-
--nowValue:当前元素值;
-
--nowIndex:当前索引;
-
--arr:调用 reduce 的数组;
- 参数说明:
- array.reduce(function(preValue, nowValue, nowIndex, arr){}, initialValue)
- 注意:
-
1.如果initialValue在调用时被提供,那么第一次的preValue就等于initialValue,nowValue等于数组中的第一个值;
-
2.如果initialValue未被提供,那么preValue等于数组中的第一个值,nowValue自动等于数组中的第二个值。
封装代码
<script type="text/javascript">
function sendAjax(url,method,data) {
return new Promise((resolve,reject)=>{
//1.创建xhr对象
let xhr = new XMLHttpRequest()
//2.绑定监听
xhr.onreadystatechange = function () {
if(xhr.readyState !== 4){
return
}
if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status<= 299)){
const responseObj = {
data:xhr.response,
status:xhr.status,
statusText:xhr.statusText
}
resolve(responseObj)
}else{
reject(new Error('请求出错了'))
}
}
//3.设置请求的方式,地址,携带的参数
let dataKeys = Object.keys(data)
//4.将传递过来的数据对象查询字符串形式的编码
let str = dataKeys.reduce(function (pre,now) {
return pre+=`${now}=${data[now]}&`
},'')
//5.发送请求
if(method.toLowerCase() === 'get'){
url += `?${str}`
xhr.open(method,url)
xhr.send()
}else if (method.toLowerCase() === 'post'){
xhr.open(method,url)
//设置请求头
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
xhr.send(str)
}
})
}
</script>
调用
.then.catch方法或是async/await异步调用
let btn = document.getElementById('btn')
let btn1 = document.getElementById('btn1')
btn.onclick = function () {
sendAjax('url','GET',{x:3,y:4}).then((data)=>{
console.log(data)
}).catch((err)=>{
console.log(err)
})
}
btn1.onclick = function () {
sendAjax('url','POST',{m:1,n:2}).then((data)=>{
console.log(data)
}).catch((err)=>{
console.log(err)
})
}
//------------------------------------------------------------------------------------
;(async()=>{
let {data} = await sendAjax('url','GET',{m:1,n:2})
let {data2} = await sendAjax('url','POST',{data})
})()