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
    
  • 相关阅读:
    实验6 多态性
    js实现图片轮播
    xcode 4.6 使用NSURLConnection 获取网页内容(iOS6.1,纯手工编码,无xib,无storyboard)
    蓝牙API
    php使用microtime(true)查看代码执行时间
    clover无缘无故隐藏书签栏原因
    RedisGEO
    mysql 新特性之geometry
    mysql中geometry类型的简单使用
    微软Windows Phone 7新特性详解 狼人:
  • 原文地址:https://www.cnblogs.com/jackson-yqj/p/9783095.html
Copyright © 2011-2022 走看看