前端基础24:ES6基础 ...简单用法/箭头函数

199 阅读2分钟

ES6

解构赋值

  • 由于数组是有顺序的,x表示数组的第一项,y表示数组的第二项......
    • x,y,z既声明又定义
    • let [x,y,z] = ary;
    • let [x,,z] = ary; //中间这一项表示空项
    • let [x, [a, b = 30], y] = [10, [5], 15];
    • console.log(x, a, b, y); //解构时拿不到值则是undefined
  • let [...arr] = ary;//克隆数组
  • 交换c和d的值
    • let c = 5, d = 10;
    • [c, d] = [d, c];
  • 对象解构赋值
    • let obj = {name: "a", age: 13};
    • 由于对象没有顺序,所以解构时变量名要与属性名一样
    • let {name: n, age, hobby = "sleep"} = obj; //:表示修改变量名 如将name修改成n
  • 对象和数组的嵌套解构赋值
    • let ary2 = {a: 10, b: [20, 30], c: "ss"};
    • let {a, b: [e, f], c} = ary2;
    • console.log(a, e, f, c);

...拓展运算符,展开运算符,剩余运算符

  • 1.合并
	let ary5 = [10,20,50,60];
	let ary6 = [30,40];
	let ary7 = [...ary5,...ary6];
	console.log(ary7);//[10, 20, 50, 60, 30, 40]
	let [,...arr1] = ary5;
	console.log(arr1);//[20, 50, 60]
  • 2.数组克隆
	let [...arr] = ary5;
	console.log(arr);
	console.log(Math.max(...arr));//[10,20,50,60]
 let o1 = {n:10,m:20};
 let o2 = {a:30,b:40};
 let o = {...o1,...o2};
 console.log(o);//{n: 10, m: 20, a: 30, b: 40}
  console.log(o2);//{a: 30, b: 40}
 let {...o3} = o1;
 console.log(o3);//{n: 10, m: 20}
 console.log(Object.assign(o1, o2));{n: 10, m: 20, a: 30, b: 40}
function fn(...arr) {
    console.log(arr);//10 20
    console.log(arguments);//10 20
}
fn(10,20,30);

function fn(x,y=30) {
    console.log(x, y);//undefined 30
}
fn();
  • 参数可以是对象,数组,可以解构赋值
function ajax({url="",method="get"}) {
    console.log(url, method);

}
ajax({});//" " get
ajax({method:"post"});//" " post

箭头函数 参数部分=>函数体部分

  • 若函数体只有一行,并且有返回值,直接写return后面的内容,return可以省略
let fn = a => a+10; 
console.log(fn(20));//30
function fn(a,b) {
    let total = null;
    total = a+b;
    return total;
}
//等价于下面
let fn = (a,b) =>{
         let total = null;
         total = a+b;
         return total;};
console.log(fn(10, 20));
let fn = a => (c, d) => a + c + d
//等价于下面
function fn(a) {
    return function (c, d) {
        return a + c + d;
    }
}
  • 数组排序箭头函数
	let ary = [10,3,5,6,7,9];
	ary.sort((a,b)=>a-b);

箭头函数和普通函数的区别

  • 箭头函数没有this,会往上级作用域查找,若没有找到继续查找,直到找到window
  • 箭头函数中没有arguments
  • 不要定义成构造函数
  • 不支持call,bind,apply改变箭头函数的this,因为箭头函数没有this
function sum() {
    console.log(this);
    window.setTimeout(function () {
        console.log(this);
    },1000)
}
sum.call(obj2);

将上面函数两个this改变指向相同

  • 方法1
function sum() {
    console.log(this);//{num: 20}
    let that = this
    window.setTimeout(function () {
        console.log(that);//{num: 20}
    },1000)
}
sum.call(obj2);
  • 方法2
function fn2() {
    console.log(this);//{num: 20}
}
function sum() {
    console.log(this);//{num: 20}
    window.setTimeout(fn2.bind(this),1000);
}
sum.call(obj2);
  • 方法3
function sum() {
    console.log(this);//{num: 20}
    window.setTimeout(()=>{
        console.log(this);//{num: 20}
        },1000)
}
sum.call(obj2);