ES7 Feature Summary

I don't know how the features of ES6 have been learned by my friends? Both ES2016 (ES7) and ES2017 (ES8) are coming out. This article will introduce the new features of ES7 for you.

ES7 Features

There are only two ES7 features:

  • Array.prototype.includes
  • Exponentiation Operator **

Array.prototype.includes

Array.prototype.includes(value:任意值): boolean

includes() The method is used to determine whether an array contains a specified value. According to the situation, it returns true if it contains, otherwise it returns false.

let a = [1, 2, 3];

a.includes(2); // true 

a.includes(4); // false

grammar:

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)

Seeing this, you will feel that it is very similar to the indexOf method.

[1, 2, 3].includes(1)   // true
[1, 2, 3].indexOf(1)    // 0

But one thing is different from indexOf, the includes() method can find NaN, but  indexOf() not:

[NaN].includes(NaN)    //true
[NaN].indexOf(NaN)     //-1

Next we look at polyfil

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);
      
      var len = o.length >>> 0;

      if (len === 0) {
        return false;
      }

      var n = fromIndex | 0;

      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      while (k < len) {
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      return false;
    }
  });
}

You can see includes()that the implementation of the method is to use the while loop array, if the searchElement is found, it will return true, otherwise it will return false.

Exponentiation Operator **

In ES6, if you want to do some exponentiation, you need to use Math.pow(x, y)methods,

Now in ES7/ES2016, developers with MathWizard can use the shorter syntax:

let a = 7 ** 12
let b = 2 ** 7
console.log(a === Math.pow(7,12)) // true
console.log(b === Math.pow(2,7)) // true

**is an operator, like +, -, *, /and also

let a = 7
a **= 12
let b = 2
b **= 7
console.log(a === Math.pow(7,12)) // true
console.log(b === Math.pow(2,7)) // true

Reference reading:

  1. https://www.cnblogs.com/zhuanzhuanfe/p/7493433.html
  2. https://w3ctech.com/topic/1614
  3. https://www.jianshu.com/p/a138a525c287
  4. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#BrowserCompatibility

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326823108&siteId=291194637