"Introduction to ES6 Standards" reading notes __ Reading notes

Source: Internet
Author: User
Tags constant hypot numeric value shallow copy square root

Spring Festival at home Idle Nothing, to see ES6, selected Ruan a peak big "ES6 Standard Primer" This book, understand the new JS specification. Here to do some reading notes. ECMAScript 6 Notice

Currently, the newer versions of the major browsers should support ES6, and the Node.js support for ES6 is higher than the browser, and can experience more ES6 features through node. Babel transcoding device

Babel is a ES6 transcoding that converts ES6 code to ES5 code, which can be performed in an existing environment. In other words, you can write programs in a ES6 way without worrying about whether your existing environment supports them.
There is also a traceur transcoding device is the same effect. Let and const commands Let command

Basic usage: let is used to declare variables, like Var, but the life variables are valid only in the code block where the Let command is located. For loop counter I, it's good to use the Let command so I only works within the For loop.

var a = [];
for (var i = 0; i < i++) {
A[i] = function () {
console.log (i);}
A[6] (); Ten

var a = [];
for (Let i = 0; i < i++) {
A[i] = function () {
console.log (i);}
;
}
A[6] (); 6

let unknown var that will occur "variable elevation" phenomenon, so the variable must be declared before use, otherwise it will be an error.

In simple terms, variable ascension is to automatically resolve the definition of the variable in advance, so that even if first used, after the definition of variables, the program can also run normally. Notice here, however, that the variable is promoted, only to declare the variable in advance, and not to assign a value. See the following example:

Console.log (foo); Output undefined
console.log (bar);//Error referenceerror
var foo = 2;
Let bar = 2;

The var foo variable is promoted, but the promotion is defined, not assigned, so it is undefined, and let bar does not have a variable elevation, and it directly complains

About variable/function elevation

A function can only be promoted by declaring a form. Anonymous function assignment cannot be promoted.

in short, the variable is not available in the code block until the variable is declared using the Let command. Become "Temporary Dead Zone" (TDZ) syntactically

if (true) {
//TDZ starts
tmp = ' abc ';//Referenceerror
Console.log (TMP);//Referenceerror let
tmp;//Tdz End C8/>console.log (TMP); Undefined
tmp = 123;
Console.log (TMP); 123
}

If you use typeof before the Let declaration variable, you will also get an error. Do not declare without error.

let does not allow duplicate declarations block-level scopes for ES6

Let actually added a block-level scope to JS.

Function F1 () {let
n = 5;
if (true) {let
n = ten;
}
Console.log (n); 5
}

The top function has two blocks of code, all declared N, run output 5, which shows that the outer code block is not affected by the inner layer of code block, if here with Var, the last output of N is 10. Const Command

Const declares a read-only constant that, once declared, initializes the copy immediately, and then the value of the constant cannot be changed.

The const scope is the same as let: only valid within the block-level scope where the declaration resides. And there is no variable elevation, it must be declared before use. and cannot duplicate the declaration

A const-declared object that only points to an object's address is invariant, and the object itself is mutable. But cannot be assigned a value
An array of const declarations, which can be used with a push method, but cannot be assigned a value

Starting with ES6, global variables are gradually decoupled from the properties of the global object. Let,const,class declared global variables that are no longer part of the global object's properties:

var a = 1
window.a//1 let
b = 1;
WINDOW.B//undefined
the deconstruction assignment of a variable

ES6 allows values to be extracted from arrays and objects in a certain pattern, assigning values to variables, which is called deconstruction.

Such as:

ES5 value
var a = 1;
var b = 2;
var c = 3;
ES6  value
var [a,b,c] = [1,2,3];
As long as both sides of the equals pattern are the same, the left variable is assigned the corresponding value.

If the deconstruction is unsuccessful, the value of the variable equals undefined

In fact, there are incomplete deconstruction:

let [x, y] = [1, 2, 3];
X//1
y//2 let
[A, [b], d] = [1, [2, 3], 4];
A//1
b//2
D//4

object to be refactored with the same variable name:

var {bar, Foo} = {foo: "AAA", Bar: "BBB"};
Foo//"AAA"
Bar//"BBB"
var {baz} = {foo: "AAA", Bar: "BBB"};
Baz//undefined

String Deconstruction:

const [A, B, C, D, e] = ' Hello ';
The a-e are H,e,l,l,o, respectively.

Value/Boolean deconstruction:

let {tostring:s} = 123;
s = = Number.prototype.toString//True let
{tostring:s} = true;
s = = Boolean.prototype.toString//True

function argument deconstruction:

function Add ([x, Y]) {return
x + y;
}
Add ([1, 2]); 3

purpose of Deconstruction:
1. Value of exchange variable: [x,y] = [Y,x]
2. function returns multiple values.
3. Definition of function parameters
4. Extract JSON data:

var jsondata = {
id:42,
status: "OK",
data: [867, 5309]
};
Let {ID, status, data:number} = Jsondata;
Console.log (ID, status, number);
"OK", [867, 5309]
extension of String

Includes (): Returns a Boolean value that indicates whether the parameter string was found.
StartsWith (): Returns a Boolean value that indicates whether the parameter string is in the head of the source string.
EndsWith (): Returns a Boolean value that indicates whether the parameter string is at the end of the source string.
Repeat (): Returns a new string indicating that the original string is repeated n times.
Padstart (): Full string from head
Padend (): extension from tail-complement full string value

Number.isfinite () is used to check whether a numeric value is finite (finite).
Number.isnan () is used to check whether a value is Nan.
ES6 the Global Method parseint () and parsefloat () to the number object, and the behavior remains intact. Number.parseint (), Number.parsefloat ()
Number.isinteger () is used to determine whether a value is an integer.

ES6 on the Number object, add a minimal constant number.epsilon. Set the error range for the floating-point number calculation, because we know that the JS floating-point count is not accurate. But if this error can be less than Number.epsilon, we can assume that the correct result is obtained. Therefore, the essence of Number.epsilon is an acceptable error range.

Number.issafeinteger () is used to determine whether an integer falls between -2^53 and 2^53 (excluding two endpoints), exceeding this range and cannot accurately represent this value. extension of the Math object

The Math.trunc method is used to remove a decimal part of a number and to return an integer part. For Non-numeric, Math.trunc uses the number method internally to convert first to a numeric value.

The Math.sign method is used to determine whether a number is positive, negative, or zero.

The MATH.CBRT method is used to compute the cubic root of a number. For Non-numeric, the MATH.CBRT method also uses the number method to convert it to a numeric value first.

The Math.hypot method returns the square root of the sum of squares of all parameters. If the parameter is not a numeric value, the Math.hypot method converts it to a numeric value. As long as one parameter cannot be converted to a numeric value, Nan is returned.

Number of logarithmic methods.
Trigonometric functions of several methods.

new exponential operator:
ES7 has added an exponential operator (* *), which is currently supported by the Babel transcoding device. 2 * * 3//8 expansion of the array

The Array.from method is used to convert two classes of objects into real arrays: objects that resemble arrays (Array-like object) and Traversal (iterable) objects, including ES6 new data structure set and
MAP). In practice, a common array-like object is the NodeList set returned by the DOM operation, and the arguments object within the function. Array.from can convert them into real arrays.

NodeList Object Let
ps = Document.queryselectorall (' P ');
Array.from (PS). ForEach (function (p) {
console.log (p);
});
Arguments object
function foo () {
var args = array.from (arguments);
// ...
}

In the code above, the Queryselectorall method returns an array-like object that can only be used using the Foreach method if it is converted to a real array.

The Array.of method is used to convert a set of values to an array.

Array.of (3, 8)//[3,11,8]
array.of (3)//[3]
Array.of (3). Length//1

The Copywithin method of an array instance, within the current array, to copy the members of the specified position to another location (overwriting the existing member) and then return the current array. In other words, using this side
method, the current array is modified.
Array.prototype.copyWithin (target, start = 0, end = this.length)
It accepts three parameters.
Target (required): Replaces data from this location.
Start (optional): Reads data from this location, defaults to 0. If negative, the reciprocal is represented.
End (optional): Stops reading data before this location, and is equal to the length of the array by default. If negative, the reciprocal is represented.
These three parameters should be numeric and, if not, automatically converted to numeric values.

[1, 2, 3, 4, 5].copywithin (0, 3)
//[4, 5, 3, 4, 5]
//The above code indicates that the members (3rd and 4) that will be from the 5 bit until the end of the array are copied to the position starting at No. 0 digits, with the result covering the original 1 and 2.

The Find method of an array instance that is used to locate the first qualified array member. Its argument is a callback function, and all the array members execute the callback function sequentially until the first return value is found
is a member that is true, and then returns the member. Returns undefined if there are no eligible members.

The use of the FindIndex method of an array instance is very similar to the Find method, which returns the position of the first qualifying array member, or 1 if none of the members meet the criteria.

The Fill method populates an array with the given value. The Fill method can also accept the second and third arguments that specify the starting and ending positions of the fill.

[' A ', ' B ', ' C '].fill (7, 1, 2)
//[' A ', 7, ' C ']
////The above code indicates that the Fill method starts at 1th digits, fills 7 to the original array, and ends before the 2nd digit number.

ES6 provides three new methods--entries (), keys (), and values ()--for traversing arrays. They all return a traversal object (see the chapter "iterator") to
The only difference is that the keys () are traversal of key names, values () are traversal of key values, and entries () is the traversal of key-value pairs, using the For...of loop for traversal.

The Array.prototype.includes method returns a Boolean value that indicates whether an array contains a given value, similar to the includes method of the string. The method belongs to ES7, but the Babel transcoding device
Already supported. Before this method is used, we usually use the IndexOf method of the array to check whether a value is included. But indexof is not semantic enough, and internal use = = easy to lead to miscarriage of

The empty space of an array means that there is no value in one of the arrays. For example, the array constructor returns arrays that are empty. Array (3)//[,,,,], and Array (3) returns an array of 3 vacancies.
ES6 is clearly turning the vacancy into a undefined.
The Array.from method converts the empty space of an array to undefined, which means that the method does not ignore the empty space. Extensions of Functions

Before ES6, you cannot specify a default value directly for the parameters of a function, only the alternative method can be used. Such as:

function log (x, y) {
y = y | | ' World ';
Console.log (x, y);
}

ES6 allows you to set a default value for the parameters of a function, which is written directly after the parameter definition.

function log (x, y = ' world ') {
console.log (x, y);
}
Log (' hello ')//Hello World
log (' Hello ', ' country ')//hello '
log (' Hello ', ')//Hello

ES6 introduces the rest parameter (in the form "...)." Variable name "To get the extra parameters of the function so that you do not need to use the arguments object. The rest parameter is paired with an array of variables that will
The extra arguments are placed in the array.

function Add (... values) {let
    sum = 0;
    For (var val of values) {
        sum = val;
    }
    return sum;
}
Add (2, 5, 3)//10
extension Operators

The extension operator (spread) is a three point (...). )。 It is like the inverse of rest parameters, converting an array to a comma-delimited sequence of parameters.

function push (array, ... items) {
    Array.push (... items);
}
function add (x, y) {return
    x + y;
}
var numbers = [4];
Add (... numbers)//The
above code, Array.push (... items) and add (... numbers) These two lines, are called functions, all of them use the extension operator. The operator changes an array to a parameterized
column.

application of extension operators:

New methods for merging arrays:
//ES5
[1, 2].concat (more)
//ES6
[1, 2, ... more]
//String to array:
[... ' Hello ']
//["H", "E", "L", "L", "O"]

The Name property of the function that returns the function name of the function. Arrow Function

ES6 allows you to define functions using the arrows (=>). var function name = (parameter) => return;

var f = v => v;
Equivalent to
var f = function (V) {return
V;
};

If the arrow function requires no arguments or requires more than one argument, a parenthesis is used to represent the parameter portion.
var f = () => 5;
Equivalent to
var f = function () {return 5};

var sum = (NUM1, num2) => num1 + num2;
Equivalent to
var sum = function (NUM1, num2) {return
    num1 + num2;
};

Arrow functions can be used in conjunction with variable deconstruction.

Const FULL = ({i, last}) =>-i + last;
Equivalent to
function full [person] {return
Person.first + ' + person.last;
}

The arrow function makes the expression more concise.

Const IsEven = n => n% 2 = 0;
Const SQUARE = n => n * n;
With just two lines in the code above, two simple tool functions are defined. If you don't use the arrow function, you might want to occupy more than a line, and it's not as eye-catching as it is now.

note points using the arrow function:
(1) The This object in the function body is the object in which it is defined, not the object in which it is used.
(2) can not be used as a constructor, that is, you cannot use the new command, or an error will be thrown.
(3) You cannot use the arguments object, which does not exist in the function body. If you want to use it, you can replace it with the rest parameter.
(4) The yield command cannot be used, so the arrow function cannot be used as a generator function.

Tail call is an important concept of functional programming, very simple in itself, which means that the last step of a function is to call another function.
function calls itself, called recursion. If the tail calls itself, it is called tail recursion. Recursion is very memory-intensive, because there are hundreds of call frames that need to be saved at the same time. "Stack Overflow" error (stack overflow) is very easy. But for the tail-handed return, there is only one call
Frames, so "stack Overflow" errors never occur. extension of the object

ES6 allows you to write directly to variables and functions as objects ' properties and methods. Such writing is more concise.

var foo = ' Bar ';
var baz = {Foo};
Baz//{foo: "Bar"}
//equivalent to
var baz = {Foo:foo};
The code above indicates that ES6 allows only the property name to be written in the object, not the property value. At this point, the property value is equal to the variable represented by the property name.
function f (x, y) {return
    {x, y};
}
Equivalent to
function f (x, y) {return
    {x:x, y:y};
}
F (1, 2)//Object {x:1, y:2}//
except for attributes shorthand, methods can also be abbreviated:
var o = {method
    () {return
        "hello!";
    }
};
//equivalent to
var o = {
    method:function () {return
        "hello!";
    }
};

COMMONJS module Output variables, it is very appropriate to use concise writing.

var ms = {};
function GetItem (key) {return
key in MS Ms[key]: null;
}
function SetItem (key, value) {
Ms[key] = value;
}
function Clear () {
ms = {};
}
Module.exports = {GetItem, setitem, clear};
Equivalent to
module.exports = {
Getitem:getitem,
Setitem:setitem, clear
:

In ES5, only the square bracket method can be used to put an expression, ES6 allows the expression to be the property name of an object when the object is defined literally:

Let Propkey = ' foo ';
Let obj = {
    [Propkey]: True,
    [' a ' + ' BC ']: 123
};
Obj.foo//True
OBJ.ABC//123

An expression can also be used to define a method name:

Let obj = {
    [' h ' + ' Ello '] () {return
        ' Hi ';
    }
};
Obj.hello ()//Hi

The Name property of the function that returns the function names. The object method is also a function, so there is also a Name property.

ES5 compares two values for equality, with only two operators: the equality operator (= =) and the strict equality operator (= = =). They all have disadvantages, the former will automatically convert data type, the latter of Nan does not
equals itself, and +0 equals-0. JavaScript lacks an operation, and in all environments, as long as two values are the same, they should be equal.
ES6 proposed the "Same-value equality" (equal value) algorithm to solve this problem. Object.is is the new way to deploy this algorithm. It is used to compare whether two values are strictly equal and
The behavior of strict comparison operators (= = =) is basically the same.

The Object.assign method is used for merging objects, copying all enumerable properties of the source object (source) to target objects.

var target = {a:1};
var source1 = {B:2};
var source2 = {C:3};
Object.assign (target, Source1, source2);
Target//{a:1, b:2, C:3}

If there is only one argument, Object.assign returns the parameter directly. If the argument is not an object, it is first converted to an object and then returned. Because undefined and null cannot be converted to objects, they are an error if they are arguments.
Note that the Object.assign method implements a shallow copy, not a deep copy. That is, if the value of a property of the source object is an object, then the target object copy gets a reference to the object.

Extension operator (..... is used to remove all the traversal properties of the Parameter object and copy it into the current object.

Let z = {a:3, b:4};
Let n = {... z};
N//{a:3, b:4}

This equates to using the Object.assign method. Symbol

ES5 object property names are strings, which can easily cause property names to conflict. For example, you use an object provided by another person, but you want to add a new method to the object (mixin mode), the new
The name of the method may conflict with the existing method. If there is a mechanism to ensure that the names of each attribute are unique, this will fundamentally prevent the conflict of property names. It's
is why ES6 introduced symbol.
ES6 introduces a new primitive data type symbol that represents a unique value. It is the seventh data type in the JavaScript language, the first six of which are: Undefined, Null, Boolean
(Boolean), String (string), numeric value (number), objects (object).

P107

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.