[Turn] "ES6 standard" reading notes

Source: Internet
Author: User
Tags hypot square root

Source: 1190000005863641

Let and const commands
    1. The ES6 new Let command, used to declare variables, is a block-level scope.

    2. A let declared variable does not have a "variable boost" phenomenon as a variable declared by Var, so the variable must be used after the declaration, or it will be an error.

    3. Transient dead zone: Whenever a let command exists within a block-level scope, the variables it declares are "bound" to the region and are no longer affected by external influences. That is, within the code block, this variable is not available until the variable is declared with the Let command, which is syntactically called a "transient dead zone."

    4. ES6 provides for temporary dead zones and non-existent variable elevation, primarily to reduce runtime errors and prevent the use of this variable before the variable declaration, resulting in an unexpected error that is common in ES5.

    5. Let does not allow the same variable to be declared repeatedly within the same scope.

    6. The const command declares a constant and cannot be changed after it is declared, so it must be assigned at the time of Declaration, which is also a block-level scope, and also has a temporary dead zone.

    7. For objects declared with const, the variable name does not point to the object's data, but to the address where the object is located, so the data in the compound type variable declared with const can be changed, which needs to be careful!

Deconstruction Assignment of variables
  1. Deconstruction: ES6 allows you to extract values from arrays and objects in a certain pattern, assigning values to variables, which is deconstructed. As follows:

     //es5var a = 1; var B = 2; var c = 3; Es6var [A, B, c] = [1, 2, 3]; //nested let [foo, [[[Bar], Baz]] = [1, [[ 2], 3]];foo; //1bar; //2baz; //3//if the right side of the equals sign is not a structure that can be traversed, the error will be not matched.  
  2. Deconstruction assignment is allowed to set the default value, use ' = = = ' inside ES6 to determine whether a location has a value. Therefore, if an array member is not strictly equal to undefined, the default value will not take effect. For example:

     [x, y =  ' B '] = [ ' a ', undefined]; //x= ' a ', y= ' b ' [x = 1] = [null];< Span class= "hljs-comment" >//x=null         
  3. The
  4. Default value can refer to other variables that deconstruct the assignment, but the variable must already be declared. For example:

     let [x = 1, y = x] = []; Span class= "Hljs-comment" >//x=1; Y=1let [x = 1, y = x] = [2]; //x=2; Y=2let [x = 1, y = x] = [1, 2"; //x=1; Y=2let [x = y, y = 1] = []; //error because x is not declared when Y is used as its default value         
  5. object's Deconstruction Assignment:

    var {foo, bar} = {foo: "aaa", bar:"bbb"};foo //"aaa"bar //"bbb"

There is an important difference between an object's deconstruction assignment and an array: the elements of the arrays are arranged in order, the value of the variable is determined by its position, and the object's property has no order, and the variable must have the same name as the property in order to get the correct value.

  1. The destructor assignment of an object makes it easy to assign the method of an existing object to a variable. For example:

    let {log, sin, cos} = Math;//这样就可以把取对数、正弦、余弦3个方法赋值到对应的变量上面,用起来很方便;
  2. The string can also be deconstructed because the string is converted to an array-like object. For example:

    const [a, b, c, d, e] = ‘hello‘;a // ‘h‘b // ‘e‘c // ‘l‘d // ‘l‘e // ‘o‘let {length : len} = ‘hello‘;len //5
  3. destructor assignment for numeric and Boolean values: if the right side of the equals sign is a numeric or Boolean value, the object will first be converted to a value.

  4. Function parameters can also be deconstructed to assign values, for example:

    function add([x,y]){    return x + y;}add([1, 2]) //3
  5. The use of the variable's deconstruction assignment is many, concise and easy to read:

      • The value of the Exchange variable [x, y] = [y, x] ;

      • Returns multiple values from a function;

      1. Example () {

        return [1, 2, 3];

        }

      2. [A, B, c] = example ();

      • Definition of function parameters;

        //有序function f([x, y, z]){...};f([1, 2, 3]);//无序function f({x, y, z}){...};f({z:3, y:2, x:1});
      • Extracting JSON data to quickly extract data from JSON objects;

Extension of the string

ES6 strengthens support for Unicode and extends the string object.

  1. ES5 provides a Charat method for string objects that returns the character of a given position in a string. However, this method does not recognize a character with a code point greater than 0xFFFF. An at method is provided in ES7 to identify characters that have a Unicode number greater than 0xFFFF.

  2. Includes (), StartsWith (), EndsWith () method. JS only indexof method can be used to determine whether a string is contained in another string, ES6 also provides three ways:

    • Includes (): Returns a Boolean value indicating whether the parameter string was found;

    • StartsWith (): Returns a Boolean value that indicates whether the parameter string is in the header of the source string;

    • EndsWith (): Returns a Boolean value that indicates whether the parameter string is at the tail end of the source string;

  3. Repeat (), the Repeat method returns a new string indicating that the original string is repeated n times.

  4. Padstart (), Padend (): ES7 introduces the function of string complement length. If a string length does not reach the specified length, it is complete at the head or tail end. The Padstart is used for head completion and padend for tail completion. If the length of the original string is greater than or equal to the specified minimum length, the original string is returned. For example:

      ' x '. Padstart (5,  ' ab ') //' ABABX '  ' x '. Padstart (4,  ' ab ') //' Abax '  X '. Padend (5,  ' ab ') //' Xabab '  ' x '. Padend (4,  ' AB ') //' Xaba '  ' xxx '. Padstart (2,  ' ab ') //' xxx '        
The expansion of the regular
    1. In ES5, the RegExp constructor can only accept strings as arguments var regex = new RegExp("xyz", "i"); . In ES6, the RegExp constructor is allowed to accept a regular expression as a parameter, and a copy of the original regular expression is returned.

    2. ES6 adds a notation for using curly braces to denote Unicode characters, which must be added to the regular expression in order to be recognized by the U-modifier. For example:

      /\u{61}/.test(‘a‘); //false/\u{61}/u.test(‘a‘); //true
    3. ES6 adds the Flags property to the regular expression and returns the modifier for the regular expression. The Source property of ES5 returns the body of an expression.

Expansion of numeric values
  1. ES6 provides a new notation for binary and octal values, denoted by the prefix 0b (or 0B) and 0o (or 0O) respectively. Starting with ES5, in strict mode, octal values are no longer allowed with prefix 0, and ES6 is further clarified to use the 0o prefix representation.

  2. Number.isfinite (), Number.isnan (): ES6 The new two methods are provided above the number object, respectively, to examine the special values of infinite (non-infinite) and Nan.

  3. Number.parseint (), Number.parsefloat (): ES6 The Global Method parseint () and parsefloat () to the Number object. This is to gradually reduce the overall approach, so that the language gradually modular.

    //ES5parseInt(‘‘);//ES6Number.parseInt(‘‘);Number.parseInt === parseInt; //true
  4. Number.isinteger (): This method is used to determine whether a value is an integer.

  5. Added a very small constant number.epsilon, when we do the calculation, if the error can be less than this constant, then you can think the result of the calculation is correct.

  6. Number.issafeinteger (): JavaScript can accurately represent an integer range between -2{53} to 2{53}, beyond which an exact representation cannot be expressed, and the function is used to determine whether a number falls within this range.

  7. With the extension of the Math object, ES6 has added 17 math-related methods to the Math object:

    • Math.trunc (): Used to remove the fractional part and return the integer part;

    • Math.sign (): Used to determine whether a number is positive, negative or 0, the integer returns 1, the negative returns -1,0 returns 0,-0 returns 0, and the other returns Nan;

    • MATH.CBRT (): Calculates the cubic root of a number;

    • Math.clz32 (): Returns the number of 32-bit unsigned numbers that have a leading 0;

    • Math.imul (): Returns the result of two numbers multiplied by a 32-bit signed integer, returning a signed integer, for example:Math.imul(-1, 8); //-8

    • Math.fround (): Returns the form of a single-precision floating-point number;

    • Math.hypot (): Returns the square root of the sum of squares of all parameters, for example:Math.hypot(3, 4);//5

    • There are some methods related to logarithmic operation, trigonometric function operation and exponential operation.

Expansion of arrays
    1. Array.from (): Converts an array-like object and a traversed object to a true array;

    2. Array.of (): Converts a set of values into an array, for example:Array.of(3, 11, 8) //[3,11,8]

    3. Fill () method to populate the array with the given values, for example:new Array(3).fill(7) //[7,7,7]

    4. The entries (), keys (), and values () methods of an array instance are used primarily to iterate through the array, keys () is the traversal of the key name, and values () is the traversal of the key values, and entries () is the traversal of the key-value pairs;

Extension of the function
  1. ES6 can not directly specify a default value for a function's arguments, so it is often x = x || "XXX" written that ES6 allows default values to be set for the function's arguments, function test(x, y = "xxx"){}; One of the benefits of such a design is that developers can read other people's Code at a glance to see which parameters are available for saving in calling this interface. In addition, this kind of writing can be used in combination with the structure and assignment, which is very flexible.

  2. The length property of the function is modified, and if the parameter in the function has a specified default value, then length does not calculate the parameter, for example:(function(a=5){}).length;//0

  3. Scope problem, if the default value of a parameter is a variable, then the scope of the variable is the same as the scope rules of other variables, first the scope of the current function, and then the global scope;

  4. ES6 introduced the rest parameter (in the form "... Variable name ") to get the extra arguments of the function, so that you do not need to use the arguments object. The variable that is paired with the rest parameter is an array that puts the extra arguments into it, for example:

    function add(...values){    let sum = 0; for(var val of values){ sum += val; } return sum;}add(2, 5, 3); //10//add函数是一个求和函数,利用rest参数可以向该函数传入任意数目的参数。
  5. The extension operator, three dots (...), is the function of converting an array to a comma-separated sequence of arguments. For example: console.log(1,...[2,3,4],5);//1 2 3 4 5 ;

  6. The
  7. Extension operator replaces the array's apply method, and the extension operator can directly disassemble the array, for example:

     //es5< Span class= "hljs-function" >function f  (x, y, z) {}; var args = [0,1, 2];f.apply (null, args); function f  (x, y, z) {}; var args = [0,1, 2];f (... args);            
  8. The extension operator provides a new method for array merging:

    //ES5[1,2].concat(more)//ES6[1,2, ...more]
  9. The extension operator can also be combined with the deconstruction assignment;

  10. ES6 also writes the function's Name property, which can return the function name, although this property is supported by various browsers very early, but is formally written in ES6;

  11. Arrow functions: ES6 allows you to define functions using the arrow (= =), for example:

    var sum = (num1, num2) => num1 + num2;//等价于var sum = function(num1, num2){ return num1 + num2;}
  12. There are several points to note using the arrow functions:

    • The This object in the function body is the object that is defined, not the object that is used. The direction of this in JS can be changed, but the direction of this in the arrow function is constant;

    • cannot be used as a constructor. In other words, you cannot use the new command;

    • The arguments object cannot be used, and the object does not exist in the function body. If you want to use it, you can replace it with the rest parameter in ES6;

    • The yield command cannot be used, so the arrow function cannot be used as a generator function;

  13. function bindings: One of the proposals in the ES7 version after ES6 is the function binding operator (::), the double colon to the left is an object, and the right is a function. This operator automatically binds the left object as this to the function on the right, for example: foo::bar(...arguments)等价于bar.apply(foo,arguments;) . Sensory function Binding This design is very convenient, do not need to be explicitly bound to the context, look forward to the adoption of the proposal (currently Babel has supported this writing);

  14. Tail Call: means that the last step of a function is to invoke another function;

  15. Tail-Call Optimization: The tail call is different from other calls because of its special invocation location. When a function is called, a ' call record ' is formed in memory, also called a ' call frame ', which holds information such as the location of the call and internal variables. If function B is called inside function A, then a call frame of B is formed above the call frame of a. The call frame that is returned to a A, B is not gone until the execution ends. If c is called internally by B, a call frame is generated, and so on, all call frames form a ' call stack '. However, the tail call is the last step of the function, so there is no need to retain the outer function of the call frame, because the call location, internal variables and other information will not be used, directly with the inner layer function of the call frame to replace the outer function;

  16. Tail Recursion: The function call itself is called recursion, if the tail call itself is called tail recursion. Recursion is very memory intensive because it is easy to stackoverflow by saving hundreds of call frames at the same time. But for the return of the tail, there is only one call frame, so there will never be a "stack Overflow" error. For example:

     //This is a factorial function that calculates the factorial of N, which requires a maximum of n call records and a complexity of O (n). function factorial (n) {if (n = = = 1)  return 1; return n * factorial (n-1);} //rewrite into tail recursion, only one call record is used, then the complexity is O (1); function factorial (n, Totla) {if (n = = 1) return total; return factorial (n-1, n * total);}        

    This shows that the meaning of ' tail call optimization ' is significant for recursive operations, so some functional programming languages write it to language specifications. The same is true for ES6, which, for the first time, explicitly stipulates that all ECMAScript implementations must deploy ' tail-call optimization '. This means that in ES6, as long as the tail recursion is used, there is no stack overflow, saving memory.

[Turn] "ES6 standard" reading notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.