函数设置默认值
// Es6 之前写法
function oldWay(a, b) {
b = b || 1;
return a + b;
}
// es6之后写法
function newWay(a, b = 1) {
return a + b;
}
函数不定参数
function add(...params) {
let result = 0;
params.forEach(item => result += item);
return result;
}
console.log(add(1, 2, 3, 4));
箭头函数
- 声明普通方法
var oldWay = function(a, b) {
return a + b;
}
var newWay = (a, b) => a + b;
// 多行代码写法
var newWay = (a, b) => {
return a + b;
};
- 接收对象的方法
const person = {
name: "张三",
age: 21,
language: ["java", "js"]
};
// 普通写法
function printInfo(person) {
console.log("姓名:" + person.name + ",年龄:" + person.age);
}
//箭头函数写法
var printInfo = (person) => {
console.log("姓名:" + person.name + ",年龄:" + person.age);
}
// 结构化写法
function printInfo({name,age}) {
console.log("姓名:" + name + ",年龄:" + age);
}
//箭头函数 + 结构化写法
var printInfo = ({name,age}) => {
console.log("姓名:" + name + ",年龄:" + age);
}
对象合并
//方法一 使用assign函数
//将source1 source2两个的属性和值复制到target对象中
const target = {a: 1};
const source1 = {b: 1,a: 2};
const source2 = {c: 1,a: 3};
console.log(Object.assign(target, source1, source2));
//结果:{a: 3, b: 1, c: 1} 属性相同,后面的覆盖前面的
//方法二 申明式 属性相同,后面的覆盖前面的
const person = {name:"Jack",age:21,language:['java','js']};
const target = {a: 1};
const source1 = {b: 1,a: 2};
const source2 = {c: 1,a: 3};
let temp = {...person,...target,...source1,...source2};
声明对象
const name = "张三";
const age = 32;
//传统写法
let oldPerson = {name:name,age:age};
// 新写法 (如果属性名和变量名相同)
let newPerson = {name,age};
对象拷贝(深拷贝)
const person = {name:"Jack",age:21,language:['java','js']};
//将person对象所有属性和属性值拷贝到temp(深拷贝)
let temp = {...person};
数组操作
- join() 函数: 拼接数组,默认 ,拼接
let arr = [ "java", "php", "python", "大数据"];
console.log("自定义拼接数组:" + arr.join("-")); // java-php-python-大数据
- map() 函数:对数组中每个元素做处理
//将原数组字符串转数字 乘以2
let arr = ['1', '2', '3', '4'];
arr = arr.map(item => item * 2);
- reduce()函数 :对每个函数做处理,并回调处理结果
// reduce 函数的介绍:
// 为数组中每一个元素依次执行回调函数,不包括数组中被删除或者未被赋值的元素
// reduce(callback,initValue) :
// callback:回调函数,有四个入参
// 1、previousValue :上一次调用回调返回的值,或者提供的初始值
// 2、currentValue : 数组中当前处理的元素
// 3、index:当前元素在数组中的索引
// 4、arr:当前数组
// initValue:回调函数第一次默认返回值
//将数组中元素乘以2 计算累加和
let arr = ['1', '2', '3', '4'];
let temp = arr.reduce((previousValue, currentValue, index, arr) => {
console.log("上一次调用回调返回的值,或者提供的初始值:" + previousValue);
console.log("数组中当前处理的元素:" + currentValue);
console.log("当前元素在数组中的索引:" + index);
console.log("上一次调用回调返回的值,或者提供的初始值:" + arr);
return previousValue + currentValue * 2;
}, 0);
console.log(temp);
promise解决异步请求循环嵌套
传统写法
promise介绍
// 用来封装异步请求的对象
// 两个参数
// resolve:成功后要做的事情
// reject:失败后要做的事情
let p = new Promise((resolve,reject) =>{
if(true){
resolve(data);
}else{
reject(error);
}
})
//then 方法传入上次异步操作成功的返回
//catch 方法传入上次异步操作失败的返回
p.then(obj =>{
// 继续上次成功后的操作
}).catch(error =>{
})
使用案例:
第一次异步调用:
第二次异步调用,可以无限。。。。
使用promise封装异步操作
封装后使用案例: