美文网首页
Es6基础语法

Es6基础语法

作者: 糖醋鱼_ | 来源:发表于2020-06-26 08:58 被阅读0次

    ES6 函数

    1、this :this代表当前正在执行的对象

    function fn () {
      console.log(this)
    }
    fn() // window 
    const obj = new fn();  // { }
    fn.call({ name:"1" })  // { name:'1' }
    

    2、箭头函数
    (1)箭头函数的this是在定义的时候就固定不变了
    (2)箭头函数 没有自己的this
    (3)箭头函数 不能当类(构造器)使用 不可以 new
    (4)箭头函数 没有 arguments

      const fn = () => {
        console.log(this);
        console.log(arguments);
      }
      fn()   // undefined    严格模式下    在非严格模式下是 window 
      const obj = new fn();  // undefined
    

    new 一个实例 执行 4 步
    (1)创建一个空对象
    (2) 执行构造器 Person 把this指向这个 {}
    (3) 添加属性
    (4) 返回当前实例
    fn.call({ name:"1" }) // undefined

    3、怎么改变this的指向

    call ()

      function person (params) {
         this.name = params
         console.log(this.name);    //  27
       }
       person.call({},27)
    

    bind ()

      function person (params) {
        this.name = params
         console.log(this,this.name);    //  27
       }
       const fn2 = person.bind({age:22},'小花')
       fn2()
    

    ES6 数组 方法

    map filter some forEach every find findIndex reduce
    1、 map 返回一个新数组 长度不变

      const arr = [1, 3, 5, 7, 9]
    
      const newArr = arr.map(v => v+1)  // [2, 4, 6, 8, 10]
    
      const newArr = arr.map(v => v>3)   //[false, false, true, true, true]
    
      const newArr = arr.map(v => v>3 && v)   //[false, false, 5, 7, 9]
    

    2、filter 返回一个新数组 长度改变 过滤

      const arr = [1, 3, 5, 7, 9]
    
      const newArr = arr.filter(v => v>3)    //  [5, 7, 9]
    

    3、 some 只要返回true 就会停止循环

      const arr = [1, 3, 5, 7, 9]
    
      const newArr = arr.some(v => v===7)    //  返回true  循环了3次
    

    4、 every 只要返回false 就会停止循环

      const arr = [1, 3, 5, 7, 9]
    
      const newArr = arr.every(v => v===7  )    // 只执行了1次   返回false
    

    5、 foeEach 普通循环 没有返回值

      const arr = [1, 3, 5, 7, 9]
    
      arr.forEach(v => {
    
        console.log(v);  //  1, 3, 5, 7, 9
    
      }) 
    

    6、 find 为true的时候就会停止循环 返回 当前的值

      const data = [{name:'1',id:1}, {name:'2',id:2}, {name:'3',id:3}]
    
      const newObj = data.find(v => v.id===2)
    
      console.log(newObj);        //  {name:'2',id:2}
    

    7、 findIndex 为true的时候就会停止循环 返回 当前的值的下标

      const data = [{name:'1',id:1}, {name:'2',id:2}, {name:'3',id:3}]
    
      const newObj = data.find(v => v.id===2)
    
      console.log(newObj);        //  返回 1
    

    8、 reduce 两个参数 (函数[必须有return],默认值)
    (1)无默认值

    
      const arr = [1, 3, 5, 7, 9]
    
      const sum=arr.reduce((a,b)=>{
    
        return a+b
    
        // a ->1  b->3         第1次
    
        // a ->4  b->5         第2次
    
        // a ->9  b->7  ....   第..次
    
      })
    
      console.log(sum);      // 25
    

    (2)有默认值

    
    const arr = [1, 3, 1, 7, 5, 7, 9]
    
        // a ->{}  b->1              第1次
    
        // a ->{1:[1]}  b->3         第2次
    
        // a ->{1:[1],3:[3]}  b->1   第3次
    
        // a ->{1:[1,1],3:[3]}  b->7   第4次  ....
    
      const newObj = arr.reduce((a,b)=>{
    
               if (a[b]) {   a[b].push(b)   } else {   a[b] = [b]   }
    
               return a
    
      }, {})
    
      console.log(newObj);  //{1:[1, 1],3:[3],5:[5],7:[7, 7],9:[9]}
    

    (3)在antd 3.26 表单回填应用

    
      mapPropsToFields({ obj }) {
    
         return Object.keys(obj).reduce((pre, d) => {
    
            return {
    
             ...pre,
    
             [d]: Form.createFormField({ value: obj[d] })
    
            }
    
          }, {})
    
       },
    

    9、数组的扩展运算符 ...

      const arr = [1, 2, 3]
    
      const brr = [4, 5, 6]
    
      console.log([...arr,...brr]);  // [1,2,3,4,5,6]
    

    10、 fill 填充数组

      const str=new Array(50).fill('-').join('')
    
      console.log(str);  //  ---------------------
    

    11、includes 是否包含

      const arr = [1, 2, 3]
    
      console.log(arr.includes(2))   // true
    

    12、flat 数组扁平化

      const arr = [1, [2, [3,4] ] ]
    
      //  默认二维数组扁平化
    
      console.log(arr.flat() )   // [1,2,[3,4] ]
    
      //  Infinity 多维数组扁平化
    
      console.log(arr.flat(Infinity) )  // [1,2,3,4]   
    

    13、Set 数组去重

       let crr= [1,2,1,3,4,5,1,2]
    
       console.log([...new Set(crr)]);    //  [1,2,3,4,5]
    

    ES6 对象 方法

    1、Object.assign(新对象,对象1,对象2,..) 合并对象
    注: 是个浅拷贝

       const obj1 = { name:"小花" }
    
       const obj2 = { age:20 }
    
       Object.assign(obj1,obj2) // 浅拷贝   { name:"小花", age:20 }
    
       //{...obj1,...obj2}        // 浅拷贝   { name:"小花", age:20 }
    

    2、keys 取到所有的key值 values 取到所有的value值

       const obj = { name:"小花", age:20, sex:"男" }
    
       console.log(Object.keys(obj));  // ["name", "age", "sex"]
    
       console.log(Object.values(obj)); //  ["小花", 20, "男"]
    

    3、Object.entries( )

      const obj = { name:"小花", age:20, sex:"男" }
    
      Object.entries(obj)   // [ ["name", "小花"],["age", 20],["sex", "男"] ]
    

    取出对象里的所有key 和 value

    (1)、reduce

           Object.entries(obj).reduce((v,[key,value])=>{
                  console.log(key,value)           // name 小花  age 20  sex 男
            },'')
    

    (2)、for of

            for(let [key,value] of Object.entries(obj)) {
                 console.log(key,value)           // name 小花  age 20  sex 男
            }
    

    ES6 Promise

    1)对象的状态不受外界影响。Promise对象代表一个异步操作,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。

    2)一旦状态改变,就不会再变,任何时候都可以得到这个结果。Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。

    image

    (1)、特点:处理异步 异步的代码以同步的方式

    (2)、用法 :
    new Promise((resolve,reject)=>{ resolve() 成功 reject() 失败 })
    (3)、状态:进行中 已成功 已失败 (一旦固定就不会再改变)

    1、 Promise.all() -- 用于将多个 Promise 实例,包装成一个新的 Promise 实例 两个promise一起触发

    const url = "http://api.baxiaobu.com/index.php/home/v1/register"
    
    const param = qs.stringify({
    
      username:"1111",
    
      pwd:"222"
    
    })
    
    const fn0 = () => axios.post(url,param)
    
    const fn1 = () => axios.post(url,param)
    
    const p0 = Promise.all([fn0(),fn1()])
    
    p0.then(res=>console.log(res))
    
    .catch()
    

    2、 async 和函数一起用 函数里需要异步方法前面加上 await
    await 不止异步 任何值 两个promise逐步触发

    const URL="https://blogs.zdldove.top/Home/Apis/listWithPage"
    async function fn () {
        const res0 = await axios.post(URL)
        console.log(1);
        const res1 = await axios.post(URL)
        console.log(res0,res1);
    }
    fn()
    

    3、async 原理
    async === generator + 自动执行器

    function spawn (genF) {
      return new Promise((resolve, reject) => {
        const gen = genF()
        function step (nextF) {
          let next = nextF()
          if(next.done) {
             return resolve(next.value)}    
             Promise.resolve(next.value)
              .then(v => {
                 step(() => gen.next(v))
              })
          }
        step(() => gen.next(undefined))
      })
    }
    

    ES6 解构赋值

    1、数组的解构赋值

    ES5:
    var a = 1;
    var b = 2;
    ES6:
    var [a,b] = [1,2]
    以上模式匹配写法
    

    数组嵌套解构

    let [a,[[b],c]] = [1,[[2],3]];
    a//1
    b//2
    c//3
    let [arr,..brr] = [1,2,3,4];
    arr//1
    brr//[2,3,4]
    

    如果解构不成功,变量的值就是undefined

    let [a] = [];
    let [b,a] = [1];
    // a就是undefined
    

    Set解构,也可以使用数组的解构赋值

    let [x,y,z] = new Set(["a","b","c"]);
    x //a
    

    2、对象解构赋值

    对象的解构与数组的解构有一个重要的不同;数组的元素是按次序排列的,变量的取之由他的位置决定;而对象的属性是没有次序的,变量必须与属性同名,才能取到正确的值

    let {bar,foo} = {foo:"aaa",bar:"bbb"};
    bar // bbb
    foo //aaa
    let {baz,foo} = {foo:"aaa",bar:"bbb"};
    baz //属性不同名是 undefined
    

    3、数值和布尔值的解构赋值

    解构赋值时,若果右边是数值或者布尔值,则会先转成对象

    let {toString:s} = 123;
    s === Number.prototype.toString //true
    let {toString:s} = true;
    s === Boolean.prototype.toString //true
    //undefined和null无法转为对象,所以对他们解构赋值就会报错
    

    相关文章

      网友评论

          本文标题:Es6基础语法

          本文链接:https://www.haomeiwen.com/subject/hsyyfktx.html