zoukankan      html  css  js  c++  java
  • ES7的新特性

    ES7的新特性

    ES7 特性:

    1.Array.prototype.includes
    2.Exponentiation Operator(求幂运算)

    一,Array.prototype.includes

         Array.prototype.includes用法容易和简单。它是一个替代indexOf,开发人员用来检查数组中是否存在值,indexOf是一种尴尬的使用,因为它返回一个元素在数组中的位置或者-1当这样的元素不能被找到的情况下。所以它返回一个数字,而不是一个布尔值。开发人员需要实施额外的检查。在ES6,要检查是否存在值你需要做一些如下的小技巧,因为他们没有匹配到值,Array.prototype.indexOf返回-1变成了true(转换成true),但是当匹配的元素为0位置时候,该数组包含元素,却变成了false。includes在一个数组或者列表中检查是否存在一个值。

    let arr = ['react', 'angular', 'vue']
    
    // WRONG
    if (arr.indexOf('react')) { // 0 -> evaluates to false, definitely as we expected
      console.log('Can use React') // this line would never be executed
    }
    
    // Correct
    if (arr.indexOf('react') !== -1) {
      console.log('Can use React')
    }
    

    使用一点点hack 位运算符 ~ 使代码更加紧凑一些,因为~(位异或)对任何数字相当于-(a + 1):

    let arr = ['react', 'angular', 'vue']
    
    // Correct
    if (~arr.indexOf('react')) {
      console.log('Can use React')
    }
    

    在ES7中使用includes代码如下:

    let arr = ['react', 'angular', 'vue']
    
    // Correct
    if (arr.includes('react')) {
      console.log('Can use React')
    }

    同时还可以在字符串中使用includes代码如下:

    let str = 'React-Native'
    
    // Correct
    if (str.toLowerCase().includes('react')) {  // true
      console.log('Found "react"')  
    }

    二,Exponentiation Operator(求幂运算)**

    求幂运算大多数是为开发者做一些数学计算,对于3D,VR,SVG还有数据可视化非常有用。在ES6或者早些版本,你不得不创建一个循环,创建一个递归函数或者使用Math.pow,在ES6/2015ES,你能使用Math.pow创建一个短的递归箭头函数

    calculateExponent = (base, exponent) => base*((--exponent>1)?calculateExponent(base, exponent):base)
    console.log(calculateExponent(7,2) === Math.pow(7,2)) // true
    console.log(calculateExponent(2,7) === Math.pow(2,7)) // true

    在ES7 /ES2016,以数学向导的开发者可以使用更短的语法:

    let a = 7 ** 2
    let b = 2 ** 7
    console.log(a === Math.pow(7,2)) // true
    console.log(b === Math.pow(2,7)) // true
    
  • 相关阅读:
    Atitti  css   transition Animation differ区别
    Atitit 游戏引擎物理系统(1)爆炸效果
    Atitit.rsa密钥生成器的attilax总结
    新特性AAtitti css3 新特性attilax总结titti css
    Atitit 异常的实现原理 与用户业务异常
    Atitit.uke 团队建设的组织与运营之道attilax总结
    atitit 业务 触发器原理. 与事件原理 docx
    Atitit 基于dom的游戏引擎
    Atitit 团队建设的知识管理
    Javascript判断页面刷新或关闭的方法(转)
  • 原文地址:https://www.cnblogs.com/jackson-yqj/p/9783095.html
Copyright © 2011-2022 走看看