ECMAScript 6.0 (ES6) is the next generation standard for the JavaScript language. It was released in June 2015. Its goal is to make JavaScript an enterprise-level development language that can be used to write complex, large-scale applications.

ES5- Array method review

forEach

The forEach() method performs the provided function once on each element of the array. Function equivalent to for loop. Application scenario: Bind event handlers for some of the same elements! Requirement: Traversal number group [” Zhang Fei “,” Guan Yu “,” Zhao Yun “,” Ma Chao “]

var arr = ["Zhang fei"."Guan yu"."Zhaoyun"."D"];
// The first argument: element, each element of the array
// The second argument: index, the index of the array
// The third argument: array, the array being traversed
arr.forEach(function(element, index, array){
 console.log(element, index, array);
});
Copy the code

some

The some() method traverses an array to check whether the elements in the array satisfy the specified condition (provided by the function). The some() method executes each element of the array in turn: if one element meets the criteria, the expression returns true, and the remaining elements are not checked. If no element satisfies the condition, false is returned. [2,4,6,8,10,9] find if there are any elements in the array that satisfy our condition. Return “turn”, return “false”

var arr = [2.4.6.8.10.21];
// The first argument: element, each element of the array
// The second argument: index, the index of the array
// The third argument: array, the array being traversed
// Return value: A Boolean value that returns true whenever one of the callback functions returns true
var flag = arr.some(function(element, index, array){
 console.log(element, index, array);
 if(element %2= =1) {return true;
}else {
   return false; }});console.log(flag);//true
Copy the code

filter

Returns a new array. The new array elements are all elements that meet the criteria we specified. Returns a new array if we return true in the callback, then we keep it, if we return false, then we discard the requirement: Go through the array and delete the values in the array where the salary exceeds 5000 [1000, 5000, 20000, 3000, 10000, 800, 1500]

var arr = [1000.5000.20000.3000.10000.800.1500];
// The first argument: element, each element of the array
// The second argument: index, the index of the array
// The third argument: array, the array being traversed
// Return value: a new array containing all elements that return true
var newArray = arr.filter(function(element, index, array){
 if(element > 5000) {
   return false;
}else {
   return true; }});console.log(newArray);//[1000, 5000, 3000, 800, 1500]
Copy the code

map

The map() method returns a new array whose elements are the values of the original array. The map() method processes the elements in their original array order. Note: Map () does not detect empty arrays. Note: Map () does not change the original array.

Requirement: Iterate over a number array, square each item in an array Scenario: operate on each item without filtering

var arr = [1.2.3.4.5];  // 1 4 9 16 25
// The first argument: element, each element of the array
// The second argument: index, the index of the array
// The third argument: array, the array being traversed
// Return value: a new array, each element is the result of the callback function.
var newArray = arr.map(function(element, index, array){
 return element * element;
});
console.log(newArray);/ /,4,9,16,25 [1]
Copy the code

every

The every() method iterates over the array to see if all elements of the array meet the specified criteria (provided by the function). The every() method uses the specified function to detect all elements in the array: if one element in the array is detected as unqualified, the entire expression returns false, and the remaining elements are not tested. Returns true if all elements satisfy the condition.

 var arr = [2.4.6.8.10.21];
 // The first argument: element, each element of the array
 // The second argument: index, the index of the array
 // The third argument: array, the array being traversed
 // Return value: A Boolean value that returns true only if all elements return true, otherwise false.
 var flag = arr.every(function(element, index, array){
   console.log(element, index, array);
   if(element %2= =0) {return true;
  }else {
     return false; }});console.log(flag);//false
Copy the code

ES6

variable

ES6 provides two keywords for declaring variables: const and let. ES6 adds the let command to declare variables. Its usage is similar to var. Variables declared by let have block-level scope only those declared in braces using the let keyword that are accessible in the current scope

{
 let a = 10;
 var b = 1;
}
​
a // ReferenceError: a is not defined.
b / / 1

Copy the code

There is no variable promotion

// let
console.log(bar); / / error ReferenceError
let bar = 2;
Copy the code

Duplicate declarations are not allowed

let a = 10;
let a = 1;// The Identifier 'a' has already been declared
Copy the code

Const declares a read-only constant using const. Constant: a quantity whose value cannot be changed const Declared variables cannot be reassigned

const PI = 3.1415;
PI = 3; / / an error
Copy the code

Const num must be assigned to variables declared by const;

If const declares an object, only the address is guaranteed to remain the same

const obj = {name:'zs'};
obj.age = 18;/ / right
obj = {};/ / an error
Copy the code

The other uses are the same as let

  1. Can only be used within the current code block
  2. Will not raise
  3. Can’t repeat
let,const,varDifferent use ofvarThe scope of the declared variable is the function in which the statement resides, and the variable promotion phenomenon is usedletVariables declared are scoped within the block of code in which the statement resides. There is no variable promotionconstWhat is declared is a constant, and the value of that constant cannot be changed in subsequent codeCopy the code

Deconstruction assignment

Before array deconstruction, assigning values to variables can only be done directly.

let a = 1;
let b = 2;
let c = 3;
Copy the code

ES6 allows you to write it like this.

let [a, b, c] = [1.2.3];
Copy the code

Deconstructing defaults

let [a = 0, b, c] = [1.2.3];
Copy the code

Object to deconstruct

Deconstruction can be applied to objects as well as arrays. Make sure the property names are in the same order

let person = { name: 'zhangsan'.age: 20 };
Copy the code

The name variable is used to match the name attribute of the Person object, and if there is a name attribute, the attribute value is assigned to the name variable

let { name, age } = person;
console.log(name); // 'zhangsan'
console.log(age); / / 20
Copy the code

Match the Name attribute to the Person object name attribute and assign the value to the myName variable

let {name: myName, age: myAge} = person; // myName myAge belongs to an alias
console.log(myName); // 'zhangsan'
console.log(myAge); / / 20
Copy the code

Template string

In traditional JavaScript languages, output templates are written like this (jQuery’s approach is used below).

$('#result').append(
 'There are <b>' + basket.count + '</b> ' +
 'items in your basket, ' +
 '<em>' + basket.onSale +
 ' are on sale! '
);
Copy the code

This is rather cumbersome, and ES6 has introduced template strings to solve this problem.

$('#result').append(`
 There are <b>${basket.count}</b> items
  in your basket, <em>${basket.onSale}</em>
 are on sale!
`);
Copy the code
The advantages of the string template allow line breaks to use interpolation ${}Copy the code

String method

  1. Includes () : Returns a Boolean value indicating whether the specified string was found.
  2. StartsWith () : Returns a Boolean value indicating whether the argument string is at the head of the original string.
  3. EndsWith () : Returns a Boolean value indicating whether the argument string is at the end of the original string.

Array methods

find

Used to find the first element in the array that meets the criteria. If not, return undefined and some. Some returns true or false

// Get the first number greater than 10
var array1 = [5.12.8.130.44];
​
var found = array1.find(function(element) {
 return element > 10;
});
console.log(found);
Copy the code

findIndex()

Used to find the location of the first qualifying array element, or -1 if none is found

let ary = [1.5.10.15];
let index = ary.findIndex((value, index) = > value > 9);
console.log(index); / / 2
Copy the code

The includes() array can be used

Checks whether an array contains a given value, returning a Boolean value.

[1.2.3].includes(2) // true
[1.2.3].includes(4) // false
Copy the code

Function – Arrow function

The ES6 standard has a new Function: Arrow Function. Why is it called Arrow Function? Because it’s defined by an arrow:

The basic usevar fn = function(x, y) {
   console.log(x + y); } is equivalent to// Syntax: (parameter list) => {function body}
var fn = (x, y) = > {
   console.log(x + y);
}
Copy the code
Parameter Description If there is no parameter list, use () to indicate the parameter listvar sum = () = > {
   console.log('ha ha')};// Equivalent to:
var sum = function() {    
   console.log('ha ha')}; If there is only one argument, omit ()// Equivalent to:
var sum = function(n1) {    
   console.log('ha ha')};var sum = n1= > {
   console.log('ha ha')}; If you have more than one parameter, use () to enclose the parameter listvar sum = function(n1, n2) {    
   console.log('ha ha')};var sum = (n1, n2) = > {
   console.log('ha ha')};Copy the code

If the arrow function has more than one statement in the code block, enclose them in braces

var sum = function(n1) {    
   console.log('ha ha')};var sum = n1= > {
   console.log('ha ha')}; If the function body is one-line, omit {} andreturn
var fn = function(n1, n2) {
   return n1 + n2;
}
​
var fn = (n1, n2) = > n1 + n2;
Copy the code

The example has an array [1,3,5,7,9,2,4,6,8,10]. Sort the array

var arr = [1.3.5.7.9.2.4.6.8.10];
        arr.sort((a, b) = > b - a)
         console.log(arr)
Copy the code

There is an array [‘a’,’ CCC ‘,’bb’,’ DDDD ‘]. Sort the array by string length

let array = ['a'.'ccc'.'bb'.'dddd'];
        array.sort(function (a, b) {
            return a.length - b.length
        })
        console.log(array);
Copy the code

There is an array, [57,88,99,100,33,77], please keep the score above 60 points, return a new array

 var arr = [57.88.99.100.33.77];
        var newArr = arr.filter((item) = > {
            return item > 60;
        })
        console.log(newArr);
Copy the code

Note the arrow function

  1. There is no this inside the arrow function, so the this inside the arrow function points to the external this
  2. Arrow functions cannot be constructors because arrow functions do not have this

The default parameters

ES6 allows you to set default values for function arguments, which are written directly after the parameter definition.

function log(x, y = 'World') {
 console.log(x, y);
}
​
log('Hello') // Hello World
log('Hello'.'China') // Hello China
log('Hello'.' ') // HelloRest parametersfunction add(. values) {
​
}
​
add(2.5.3) / / 10
Copy the code

The remaining parameters

The residual argument syntax allows us to represent an indefinite number of arguments as an array. The undefined argument definition is a convenient way to declare a function without knowing the arguments

 function sum (first, ... args) {
    console.log(first); / / 10
    console.log(args); / / (20, 30)
}
sum(10.20.30)
Copy the code

Extension operators (expansion syntax is shallow copy)

The extension operator converts an array or object into a comma-separated sequence of arguments

let ary = [1.2.3]; . ary/ / 1, 2, 3
console.log(... ary);// 1, 2, 3, equivalent to the following code
console.log(1.2.3);
Copy the code

Extension operators can be applied to merge arrays

/ / method
let ary1 = [1.2.3];
let ary2 = [3.4.5];
let ary3 = [...ary1, ...ary2];
Copy the code
/ / method 2ary1.push(... ary2);Copy the code

Converts a pseudo-array or traversable object into a real array

let oDivs = document.getElementsByTagName('div');
oDivs = [...oDivs];
Copy the code

Array.from()

Converts a pseudo-array or traversable object into a real array

// Define a collection
let arrayLike = {
   '0': 'a'.'1': 'b'.'2': 'c'.length: 3
};
// convert to array
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
Copy the code

The map method can also take a second argument, similar to the map method of arrays, that processes each element and puts the processed value into the returned array

let arrayLike = {
    "0": 1."1": 2."length": 2
}
let newAry = Array.from(arrayLike, item= > item *2)/ / (2, 4]
Copy the code

Note: If it is an object, then the attribute needs to be indexed

Set data structure (can be used as array de-duplication)

ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values. Set itself is a constructor that generates the Set data structure const s = new Set();

The Set function can take an array as an argument to initialize.

const set = new Set([1.2.3.4.4]);/ / {1, 2, 3, 4}
Copy the code

The for of circulation

ES6 provides three new methods — entries(), keys() and values() — for traversing groups of numbers. They both return a traverser object, which can be used for… The of loop is traversed, the only differences being that keys() is traversal of key names, values() is traversal of key values, and entries() is traversal of key value pairs.

For of supports traversal of groups of numbers, class objects (such as DOM NodeList objects, also known as pseudo-arrays), strings, maps, and sets. For of does not support traversal of ordinary objects. You can use traversal with reference to object.keys () below

The Entries () method returns an iteration of an array containing the array’s key/value pairs.

for (let index of ['a'.'b'].keys()) {
console.log(index);
}
/ / 0
/ / 1
for (let elem of ['a'.'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a'.'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
Copy the code

ForEach, for in, for of

The for loop

forCan be used in a loopreturn,breakAnd so on to interrupt the cycle.var arr = [1.2.3.4]
for(var i = 0 ; i< arr.length ; i++){
  console.log(arr[i])
}
// Output the result
1.2.3.4
Copy the code

ForEach executes the supplied function once on each element of the array (no return, break, etc.) without changing the array.

let arr = ['a'.'b'.'c'.'d']
arr.forEach(function (val, index, arr) {
  // val is the current element, index is the current element index, arr is the current array
  console.log(val + ', index = ' + idx);
  console.log(arr);
});
// Output the result
a, index = 0
["a"."b"."c"."d"]
b, index = 1
["a"."b"."c"."d"]
c, index = 2
["a"."b"."c"."d"]
d, index = 3
["a"."b"."c"."d"]
Copy the code

The for… The values traversed by the in loop are the key values of the data structure. Suitable for traversing objects.

// Iterate over the object
let obj = {a: '1'.b: '2'.c: '3'.d: '4'};
for (let o in obj) {
  console.log(o);       // Iterate over the object's property names a, b, c, d
  console.log(obj[o]);  // this is the attribute's value 1,2,3,4
}
// go through the number group
let arr = ['a'.'b'.'c'.'d'];
for (let o in arr) {
  console.log(o);       // iterate over the index 0,1,2,3 of the array
  console.log(arr[o]);  // This is the corresponding value a, b, c, d
}
Copy the code

The for… A new syntax added to of ES6 to loop over a value in a key-value pair. Cannot be used on objects.

// go through the number group
let arr = ['China'.'America'.'Korea'];
for (let o of arr) {
  console.log(o); 
}
// Output the result
China, America, Korea
// Iterate over the object
let obj = {a: '1'.b: '2'.c: '3'.d: '4'}
for (let o of obj) {
  console.log(o);   //Uncaught TypeError: obj is not iterable
}
// Iterate over the string
let str = 'love';
for (let o of str) {
    console.log(o); // l,o,v,e
}
Copy the code

reduce

What it does: Receives a function as an accumulator, and each value in the array (from left to right) is reduced to a value. (fn, initialValue) fn is the parameter to calculate the function fn: (fn, initialValue) Total currentValue currentIndex arr initialValue or returned value after calculation index of the element before the current element array object to which the current element belongs initialValue is the initialValue returned value: returns the calculation result

let arr = [1.2.3.4]
let res = arr.reduce(function(prev, cur, index, arr) {
    return prev + cur;
})
console.log(arr, res); // [1, 2, 3, 4] 10
Copy the code

Array is de-duplicated and counts the number of occurrences of elements

const list = [
        { name: "left".width: 20 },
        { name: "left".width: 20 },
        { name: "right".width: 10 },
        { name: "center".width: 70 },
        { name: "right".width: 10 },
        { name: "right".width: 10},];let obj = {};
      let res = list.reduce((previous, current) = > {
        if (obj[current.name]) {
          obj[current.name]++;
          return previous;
        }
        obj[current.name] = 1;
        return[...previous, current]; } []);console.log(obj);//{ left: 2, right: 3, center: 1 }
      console.log(res);//[ { name: 'left', width: 20 }, { name: 'right', width: 10 }, { name: 'center', width: 70 }
]
Copy the code