ES6 new syntax summary

Array.prototype.keys(): Returns the value of an index object Visitor

1.Let and Const

In ES6 Previously, JSonly vara declarative way, but after ES6, it is more letwith constthese two methods. With vardefined variables no concept of block-level scope, and letwith constit will, because the creation of these three keywords is not the same

  where let const
Variable lift + - -
Global Variables    + - -
Repeat Assignment + + -  
Repeat statement + - -
Temporary dead zone - + +
Block scope - + +
Not only the declaration Assignment + + -

 

2. class (Class)

/* 匿名类 */ 
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

/* 命名的类 */ 
let Rectangle = class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

 

Before ES6, if we want to generate an instance of an object, the traditional method is to write a constructor, the following example

function Person(name, age) {
    this.name = name
    this.age = age
}
Person.prototype.information = function () {
    return 'My name is ' + this.name + ', I am ' + this.age
}
Person.distance(a,b){

    const dx = a.x - b.x;
    const dy = a.y - b.y;
    return Math.hypot(dx, dy);
  }

But after ES6, we only need to be written as follows:

class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
 // Getter
  get area() {
    return this.calcArea()
  }
 // 静态方法
  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;

    return Math.hypot(dx, dy);
  }
 // 原型方法  
 information() {
   return 'My name is ' + this.name + ', I am ' + this.age
 }

}

3. arrow function (Arrow function)

Arrow function expression syntax is more concise than function expressions, and not have their own this, arguments, superor  new.target. These function expression more suitable for those places that would otherwise require anonymous function, and they can not be used as a constructor.

4. The default value of the parameter function (Function parameter defaults)

Before ES6, if we need to write a function to define the initial value, the need to write:

function config (data) {
    var data = data || 'default'
}

This looks to be no problem, but if the argument is a Boolean value falsy will be a problem, the result will always be the value behind

const config = (data = 'data is empty') => {}

The template string (Template string)

6. deconstruction assignment (Destructuring assignment)

We destructuring assignment, that the attribute / value taken from the subject / array, assigned to other variables.

let a = 10
let b = 20
[a, b] = [b, a]

7. Modular (Module)

8. Extended operator (Spread operator)

Extended operator may be an array or string expressions in the syntax level function call when deployed / array configuration; may also be configured when the literal object, object expression expanded by way of the key-value.

const sum = (x, y, z) => x + y + z
const list = [5, 6, 7]
const total = sum(...list)

It is to be noted that the operator can only be extended for iterables

9. shorthand object properties (Object attribute shorthand)

let cat = 'Miaow'
let dog = 'Woof'
let bird = 'Peet peet'

let someObject = {
  cat,
  dog,
  bird
}

10.Promise

11.Symbol

Data type " Symbol " is a primitive data type, in that the nature of the type of value of this type can be used to create an anonymous object properties. This type of data is commonly used as an object attribute keys - when you want it to be private time

Symbol()Function returns symbol value type of the type having a static properties and static methods. It's static properties will be exposed to members of the object of several built-in; it's static methods will expose global symbol registered, and similar to the built-in object class, but as a constructor for it is not complete because it does not support syntax: " new Symbol()."

When the value of a symbol is used as a type of attribute assignment identifier, the attribute (the same as the symbol) is anonymous; and is not enumerable.

From each Symbol()value is unique symbol returned. A symbol value can be used as the object identifier attribute; this is the only purpose of the data type.

const symbol1 = Symbol();
const symbol2 = Symbol(42);
const symbol3 = Symbol('foo');

console.log(typeof symbol1); // "symbol"
console.log(symbol3.toString()); // "Symbol(foo)"
console.log(Symbol('foo') === Symbol('foo')); // false

12. iterator (Iterator) / generator (Generator)

In JavaScript, the iterator is an object that defines a sequence, and may return a return value when terminated. More specifically, by using the iterator  next() implementation  Iterator protocol  any object, the method returns the object has two properties:  valueThis is the next value in the sequence; and  done , if the last iteration has a sequence of values , then it is  true . If  value and  done present together, it is the return value of the iterator.

Once created, iterator object by repeatedly calling next () explicitly iteration. Iterator is called an iterator This iterator consumed, because it is usually only once. After generating the final value, an additional call to next () should continue to return {done: true}.

Custom iterator

function makeRangeIterator(start = 0, end = Infinity, step = 1) {
    let nextIndex = start;
    let iterationCount = 0;

    const rangeIterator = {
       next: function() {
           let result;
           if (nextIndex < end) {
               result = { value: nextIndex, done: false }
               nextIndex += step;
               iterationCount++;
               return result;
           }
           return { value: iterationCount, done: true }
       }
    };
    return rangeIterator;
}
let it = makeRangeIterator(1, 10, 2); let result = it.next(); while (!result.done) { console.log(result.value); // 1 3 5 7 9 result = it.next(); } console.log("Iterated over sequence of size: ", result.value); // 5
 

Although custom iterator is a useful tool, but because of the need to explicitly maintain its internal state, and therefore needs to be carefully created. Generator function provides a powerful option: it allows you to define a function that contains its own iterative algorithm, and it can automatically maintain their own state. Generator function uses  function*the syntax to write. Initially called, the generator function does not execute any code, but returned iterator called Generator. When consumption value by the following method a call generator, Generator function will execute until the yield keyword.

function* makeRangeIterator(start = 0, end = Infinity, step = 1) {
    for (let i = start; i < end; i += step) {
        yield i;
    }
}
var a = makeRangeIterator(1,10,2)
a.next() // {value: 1, done: false}
a.next() // {value: 3, done: false}
a.next() // {value: 5, done: false}
a.next() // {value: 7, done: false}
a.next() // {value: 9, done: false}
a.next() // {value: undefined, done: true}

 

13.for...of

for...ofIn the iteration statement objects (including  Array,Map,Set,String,TypedArray,arguments create the objects, etc.) iteration of a loop, call a custom iteration hook, and the value of the statement is executed for each different attributes.

const array1 = ['a', 'b', 'c'];

for (const element of array1) {
      console.log(element)
}

// "a"
// "b"
// "c"

14.Set/WeakSet

Set The only object allows you to store any type of value, whether it is the original value or object reference.

If a pass iterable , it will not be repeated for all the elements be added to the new  Set in. If you do not specify this parameter, or value null, the new  Set is empty.

In addition, NaNand undefinedcan be in the Set, stored  NaNbetween is considered the same value (NaN is considered to be the same, although NaN! == NaN)

const set1 = new Set([1, 2, 3, 4, 5]);

console.log(set1.has(1));
// expected output: true

console.log(set1.has(5));
// expected output: true

console.log(set1.has(6));
// expected output: false

Set.prototype.sizeReturns the Setnumber of values of the object.

Set.prototype.add(value)inSet对象尾部添加一个元素。返回Set对象。

Set.prototype.clear()Remove Setall elements within the object.

Set.prototype.delete(value)移除Set的中与这个值相等的元素,返回Set.prototype.has(value)在这个操作前会返回的值(即如果该元素存在,返回true,否则返回false)。Set.prototype.has(value)在此后会返回false。

Set.prototype.entries()返回一个新的迭代器对象,该对象包含Set对象中的By order of insertion 所有元素的值的[value, value]数组。为了使这个方法and Map对象保持相似, equal keys and values for each value.

Set.prototype.forEach(callbackFn[, thisArg])Insertion order, value for each object is called once Set callBackFn. If athisArg参数,回调中的this会是这个参数。

Set.prototype.has(value)Returns a Boolean value that indicates that the value inSet中存在与否。

Set.prototype.keys()And by the insertion order ofvalues()方法相同,返回一个新的迭代器对象,该对象包含Set对象中的所有元素的值。

Set.prototype.values()返回一个新的迭代器对象,该对象包含Set对象中的Ordered by insertion所有元素的值。

 

WeakSet The object is a collection of objects of value, and wherein the value of each object can only occur once. In the WeakSetcollection are unique

And its  Set object is the difference between two things:

  • And Setcomparison, WeakSet can be a collection of objects , but not any type of any value.
  • WeakSetHold weak references: references to objects in the collection is weak. If for no other WeakSetreferences to objects, then these objects will be treated as garbage out. This also means that there is no WeakSet list stores the current object. Because of this, WeakSet it is not enumerable.

15.Map/WeakMap

Map Object holds key-value pairs, and can remember the original insertion order button. Any value (object or primitive value ) can be used as a key or a value.

WeakMap The object is a set of key / value pairs, where the bond is weak references. Key which must be an object, and the value may be arbitrary.

16.Proxy/Reflect

Proxy  customize the behavior of objects are used to define the basic operations (such as property search, evaluation, enumerations, function calls, etc.).

let p = new Proxy(target, handler);

targetWith Proxythe target object packaged (which may be any type of object, including native array, function, or even another agent). handlerAn object whose attribute is defined as a function of the time behavior of the agent to perform an operation.

let handler = {
    get: function(target, name){
        return name in target ? target[name] : 37;
    }
};

let p = new Proxy({}, handler);

p.a = 1;
p.b = undefined;

console.log(p.a, p.b);    // 1, undefined

console.log('c' in p, p.c);    // false, 37

Reflect  is a built-in objects, methods of operation which provides JavaScript interception. These methods and proxy handlers method of the same. ReflectIt is not a function object, so it can not be constructed.

Unlike most global object different, Reflectnot a constructor. You can not be with a new operator used together, or the Reflectobject as a function call. ReflectAll the properties and methods are static (like Mathobjects).

Extended 17.Array object

Array.prototype.from(): Conversion has a Iterator接口data structure for the real list, returns the new array.

console.log(Array.from('foo')) // ["f", "o", "o"]
  console.log(Array.from([1, 2, 3], x => x + x)) // [2, 4, 6]

Array.prototype.of(): Converting a group of real value array and returns a new array.

 Array.of(7)       // [7] 
  Array.of(1, 2, 3) // [1, 2, 3]

  Array(7)          // [empty, empty, empty, empty, empty, empty]
  Array(1, 2, 3)    // [1, 2, 3]

Array.prototype.copyWithin() Method shallow copy a portion of the array to another location in the same array, and return it, without changing the length of the original array.

arr.copyWithin(target[, start[, end]])
  const array1 = ['a', 'b', 'c', 'd', 'e']

  console.log(array1.copyWithin(0, 3, 4)) // ["d", "b", "c", "d", "e"]

  console.log(array1.copyWithin(1, 3)) // ["d", "d", "e", "d", "e"]

target0 is the index of the substrate, replication sequences to that location. If it is negative, target counted from the end. If  target greater than or equal  arr.length, the copy would not occur.

If  target the  start later, the copied sequence will be modified to conform  arr.length.

start0 is the index of the substrate, to begin copying the start position of the element. If it is negative, start counted from the end. If  start ignored, copyWithin will start copying from 0.

end0 is the index of the substrate, to begin copying the end position of the element.

copyWithin It will be copied to the location, but does not include  end elements of this position. If it is negative,  end counted from the end.

If  end ignored, copyWithin the method would have been copied to the end of the array (default  arr.length)

Array.prototype.find(): Returns the first qualifying members

Array.prototype.findIndex(): Returns the first qualifying members of the index value

Array.prototype.fill(): Filling the entire array of the specified value, return to the original array

Array.prototype.keys(): Returns the value of an index object Visitor

Array.prototype.values(): Returns the object attribute value to traverser

Array.prototype.entries(): Returns the object attribute value to the index value and the walker
数组空位: a gap into an array for ES6 explicitly undefinedorempty

  Array.from(['a',,'b']) // [ "a", undefined, "b" ]
  [...['a',,'b']] // [ "a", undefined, "b" ]
  Array(3) //  [empty × 3]
  [,'a'] // [empty, "a"]

 Original link: https://mp.weixin.qq.com/s/ARBgtPuElZHLhvr1lNbAJw

Guess you like

Origin www.cnblogs.com/recode-hyh/p/12343525.html