我的作业6
# 我的作业6
# 1、
var a=1, b=[2,3], c=[4,5], d=6; 写入一个函数,将abcd以实参传入返回[1,2,3,4,5,6]
function f1(){
var arr= [];
for(var i=0; i<arguments.length; i++){
arr = [...arr.concat( arguments[i])]
}
return arr;
}f1(a,b,c,d)
# 2、
求obj对象中id与arr的和
var obj = {
id:5,
name:'abc',
sex:'男',
arr:[1,2,3,4]
};
var obj = {
id:5,
name:'abc',
sex:'男',
arr:[1,2,3,4],
getId:function(){
return this.id
},
getArr:function(){
return this.arr.reduce((prev, curr)=>{return prev+curr;})
}
}
console.log(obj.getId()+obj.getArr())
# 3、
取二组数据的并集,交集,差集并去重
var a1 = [1,2,3,4,5,6,4,5,6];
var a2 = [4,5,6,7,8,9,7,8,9];
var a3 = Array.from(new Set([...a1, ...a2])) //并集
var a4 = a2.filter(item => new Set(a1).has(item))//交集
var a5 = a3.filter(item => !a4.includes(item))//差集去重
# 4、
各结构的转换
const m1 = new Map([['a',1],['b',2],['c',3]]);
- map类型转为数组
var arr = […m1]//map转数组
- map类型转为object
var obj ={}
for(let (k,v) of m1){
obj[k]=v;
}//map转对象
- object转为map
let obj = {"name":"jindu", "qq":"2429462491"};
var map1 = new Map();
for(let k in map1){
map1.set(k,obj[k]);// obj 转map
}
- set类型转为数组
const set = new Set([1, 2, 3, 4, 5]);
var arr = Array.from([…set])
# 5、
var id = Symbol('jindu');
var o = {
[id] :'hello world',
id:'abc'
}
请求出结果:
1) o.id
// ‘abc’
2) o['id']
// “hello world”
3) o[id]
//’abc’
# 6、
promise解决回调陷阱的链式写法:
var p = new Promise(function(resolve,reject){
if(true){ //
resolve("OK")
}else {
reject("error")
}
});
p.then(function(data){
console.log(data) //
return new Promise(function(resolve,reject){
if(true){ //
resolve(1)
}else {
reject(2)
}
});
})
# 7、
Promise对象实现Ajax封装
const f1 = function(url, type, data){
const promise = new Promise(function(resolve, reject){
xmlHttp.open(type, url){
if(type =='get'){. //type get
xmlHttp.send(); //get模式带param参数
}else { //type post
xmlHttp.setRequestHeader("Content-Type", "application/json");//如post参数还有multipart/form-data其使用body调用
xmlHttp.send(JSON.stringify(data));//
};
xmlHttp.responseType = "json";
xmlHttp.onreadystatechange =function(){ //ajax请求
if (xmlHttp.readyState == 4){
if (xmlHttp.status === 200) {
resolve(xmlHttp.response);
} else {
reject(new Error(xmlHttp.statusText));
}
}
};
}
}return promise;
}