es6~ 常用语法总结

时间:2024-03-03 19:15:56
  • 声明多个变量并解构赋值
    • 解构:将对象或数组,变为多个变量
    //1. 数组解构
    let [a, b, c] = [1, 2, 3]; // 相当于 let a=1;let b=2;let c=3
    let [a, ...b] = [1, 2, 3]    //相当于 let a=1;let b=[2,3];
    let [a, b, c] = 'hel';    //相当于 let a=1;let b=2;let c=3,字符串本身是字符数组
     //2. 对象解构
    let { a, b } = { a: 'a', b: 'b' }     // 相当于 let a='a';let b= 'b';
    let {a, ...b}={a: 10, b: 20, c: 30};   //相当于 let a=10;let b={b: 20, c: 30};  
    
    
  • 简写
        //属性简写
        const age = 12; 
        const name = "Amy";
        const person = {age, name};//相当于  const person ={age: 12, name: "Amy"}
      
      //函数和函数对象参数简写
      let person={
          getName({a}){
             console.log(a);
          };
      }
    
    
  • 函数
    1. 箭头函数 : (a,b)=>{},单变量简写 a=>{}
    2. 函数参数: …args,用来代替arguments
  • …运算符
    //1. 函数参数
    function a(...param){
          console.log(param);//参数数组     
    }
    //2.剩余变量
    let [a, ...b] = [1, 2, 3]//相当于 let a=1;let b=[2,3];
    let {a, ...b}={a: 10, b: 20, c: 30};  //相当于 let a=10;let b={b: 20, c: 30};
    
    //3.解构且合并数组
    let arr1 = [1, 2]; 
    let arr2 = [3, 4];
    let arr = [...arr1, ...arr2];//相当于let arr=[1,2,3,4]
    
      //4.解构且合并对象
      let age = {age: 15}; 
      let name = {name: "Amy"}; 
      let person = {...age, ...name};//相当于  let person ={age: 15, name: "Amy"}
      
      //解构传参
     let fun= function(a,b,c){}  
     let param=[1,2,3]
     fun(...param)
    
  • 默认值
    //1.函数参数默认值
    function f(b,c=1){
       console.log(c)
    };
    f(2)//结果:1
    //2.解构默认值
    let {a=1,b}={b:2};//a=1,b=2
    let [a,b=2]=[1];//a=1,b=2
    
  • 引入了Map和Set对象
  • n次方操作符:**,eg. 2**3=8
  • Array.includes:是否包含某元素
  • async、await
    //异步函数
    async function a(){
    //await 必须在 async下使用
    await ajax();//等待完成
    await ajax2();
    
    }
    
  • flat和flatMap
    [1,2,[3,4]].flat(1) // 变为1维数组,结果:[1,2,3,4]]
    
    flatMap是map和flat的结合,下面的两个操作是等价的:
    arr.flatMap(func)
     arr.map(func).flat(1)
    
  • import () 方法:动态导入
  • String.prototype.replaceAll
        const str = "hello world";
         // 之前
         str.replace(/o/g, "a")// "hella warld"
         // 现在
         str.replaceAll("o", "a")// "hella warld"
    
  • ?? 运算符
        let a=b||'1' //b=null或undefined或0时,结果为1
        let a=b??'1' //b=null或undefined时,结果为1
    
  • ??= 空值赋值运算
        let a=2;
        a??=1 //a=null或undefined,结果为1
        console.log(a)//结果为2
    
  • ?. 对象为空时,获取其属性不报错,而获取到undefined值
       let a;
       let d=a?.b //a=null或undefined时不会报错,a.b返回undefined