Recently to revisit the ES6 document, found that in addition to the arrow function, deconstruction assignment, extension operators such common grammar, there are many very awesome method, not only make the code more concise, also can improve the robustness of the code, to my surprise, browser compatible with most of the methods, without the Babel also can perfect operation. Therefore, I felt it was necessary to clean up a bit. In the project, I abandoned the outdated writing method and upgraded to ES6 specification code.

Array upgrade

1. Extend the operator’s copy array

/ / es5 approach
const a1 = [1.2]
const a2 = a1.concat()

a2[0] = 2
a1 //[1,2] changing a2 does not affect a1
Copy the code

The extension operator provides an easy way to copy an array:

/ / es6 approach
const a1 = [1.2]
const a2 = [...a1]
//or
const [...a2] = a1

a2[0] = 2
a1 //[1,2] changing a2 does not affect a1
Copy the code

Note: This is a deep copy, but it is important to note that both concat and extension operators are shallow copies when used to merge arrays.

2. Find () and findIndex() of array instances

The find method, used to find the first eligible array member, takes a callback function that is executed until the first member whose return value is true is found, and then returned. If there is no qualified member, undefined is returned.

/ / es5 approach
const arr = [1.5.10.15]
for(var i=0; i<arr.length; i++) {if(arr[i]>5) {
        return arr[i]
    }
} / / 10
/ / es6 approach
[1.5.10.15].find(function(value,index,arr) {
    return value > 5
}) / / 10
Copy the code

In addition, both methods can find nans, compensating for the indexOf method.

[NaN].indexOf[NaN] / / 1

[NaN].findIndex(y= > Object.is(NaN,y)) / / 0
Copy the code

3. Array instance includes()

This method returns a Boolean value indicating whether an array contains a given value. In the absence of this method, we usually use the indexOf method of arrays to check for the inclusion of a value.

The indexOf method has two drawbacks. First, it is not semantic enough. It means to find the first occurrence position of the parameter value, so it is not intuitive enough to compare whether the value is not equal to -1. Second, it uses the strict equality operator (===) internally for judgment, which leads to misjudgment of NaN.

[NaN].indexOf[NaN] / / 1

[NaN].includes(NaN) / / 0
Copy the code

Note: Map and Set data structures have a HAS method. The Map has method is the Set has method that looks for the key name, which looks for the key value.

2. Object upgrade

1.Object.assign()

For merging objects, copy all the enumerable properties of the original object to the target object.

Object. Assign only the source object’s own attributes (no inherited attributes, no non-enumerable attributes).

// Add attributes and methods to the object
//es6
class Point {
 constructor(x, y) {
   Object.assign(this, {x, y}); }}ObjectPrototype, {addPoint(arg1, arg2) {··· ·}});Copy the code

This method is very common, but some details should be brought out to remind yourself.

(1) Shallow copy

The object. assign method implements shallow copy, not deep copy. That is, if the value of an attribute of the source object is an object, the target object copies a reference to that object.

(2) The replacement of the same attribute

For nested objects, once an attribute of the same name is encountered, object. assign is handled by replacement, not addition. Pay special attention!!

(3) Array processing

Object.assign works with arrays, but treats arrays as objects.

2. Traversal of attributes

ES6 has five methods for traversing an object’s properties.

(1) for… in

for… The in loop iterates over the object’s own and inherited enumerable properties (excluding the Symbol property).

(2) the Object. The keys (obj)

Keys returns an array containing the key names of all of the Object’s own (not inherited) enumerable properties (not including the Symbol property).

(3) Object. GetOwnPropertyNames (obj)

Object. GetOwnPropertyNames returns an array containing all attributes of the Object itself (excluding Symbol attribute, but cannot be enumerated attribute) of keys.

(4) the Object. GetOwnPropertySymbols (obj)

Object. GetOwnPropertySymbols returns an array containing all the Symbol attribute of the Object itself the key name.

(5) Reflect. OwnKeys (obj)

Reflect.ownKeys returns an array containing all the key names of the object itself, whether they are symbols or strings or enumerable.

Three. Function upgrade

1. The rest parameters

To get extra arguments to the function, so you don’t need to use the Arguments object.

// arguments
function sortNumbers() {
  return Array.prototype.slice.call(arguments).sort();
}

// The rest argument
const sortNumbers = (. numbers) = > numbers.sort();
Copy the code

2. Arrow function

ES6 allows functions to be defined using arrows (=>).

// arguments
function sortNumbers() {
  return Array.prototype.slice.call(arguments).sort();
}

// The rest argument
const sortNumbers = (. numbers) = > numbers.sort();
Copy the code

Note:

(1) The this object inside the function is the object at which it is defined, not the object at which it is used.

(2) Cannot be used as a constructor, that is, cannot use the new command, otherwise an error will be thrown.

(3) You can’t use arguments. This object does not exist in the function body. If you do, use the REST argument instead.

4. The for… Of circulation

for… The scope of the of loop includes arrays, Set and Map structures, some array-like objects (such as Arguments objects, DOM NodeList objects), Generator objects, and strings.

Use 1.

Array:

// Add attributes and methods to the object
//es6
const arr = ['red'.'green'.'blue'];

for(let v of arr) {
  console.log(v); // red green blue
}
Copy the code

Set and Map structures

var engines = new Set(["Gecko"."Trident"."Webkit"."Webkit"]);
for (var e of engines) {
 console.log(e);
}
// Gecko
// Trident
// Webkit

var es6 = new Map(a); es6.set("edition".6);
es6.set("committee"."TC39");
es6.set("standard"."ECMA-262");
for (var [name, value] of es6) {
 console.log(name + ":" + value);
}
// edition: 6
// committee: TC39
// standard: ECMA-262
Copy the code

An object of class array

/ / string
let str = "hello";

for (let s of str) {
 console.log(s); // h e l l o
}

// DOM NodeList object
let paras = document.querySelectorAll("p");

for (let p of paras) {
 p.classList.add("test");
}

/ / the arguments object
function printArgs() {
 for (let x of arguments) {
   console.log(x);
 }
}
printArgs('a'.'b');
// 'a'
// 'b'
Copy the code

2. Comparison with other traversal grammars

for… The in loop has several disadvantages.

  • Array keys are numbers, but for… The in loop takes strings as keys “0”, “1”, “2”, and so on.
  • for… The IN loop iterates not only over numeric key names, but also over other manually added keys, even keys on the prototype chain.
  • In some cases, for… The in loop iterates through the key names in any order. All in all, for… The in loop is designed primarily for traversing objects, not for traversing groups of numbers.

The downside of the forEach loop is that you can’t break out of the forEach loop halfway through, and neither the break or return command works.

As opposed to… Of has the following advantages:

  • Has the same for… Same concise syntax as in, but without for… In those shortcomings.
  • Unlike the forEach method, it can be used with break, continue, and return.
  • Provides a unified operation interface for traversing all data structures.

5. Refer to the website

http://es6.ruanyifeng.com/#docs/iterator#for—of-%E5%BE%AA%E7%8E%AF