ES6 study notes on the first day

## three, const, and let

**3.1 const**

const is used to define constants, so-called constant value is unchanged after once given, once defined life-long amount
const a = 10; a = 20 ;
above a is a constant, if to a re-assignment, you will a note found error:
const typically define two things:
l-defined functions
l define some special string constants and
constant name is always the all uppercase, if more than one word, separated by an underscore, suggesting that this is a constant

* the let ** 3.2 *
the let variables used to define the scope of the block-level, as long as the "{}" package, on a block-level scope.
* Note: not JSON, if seeing the body, the body functions, while, for a block, for circulating () is a block
Note: We usually use for let in, this time the automatic loop closure *:

var arr = [];
for(let i = 0; i < 10;i++){
arr.push(function(){
console.log(i);
});
}
arr[4](); //4

let and is a perfect match for, let usually futile.
var variable declarations, can be accessed from outside the for loop, resulting in variable i to the time a final value, arr [4] (though access closures, but the same i, i so that a single value).
And let each has a different corresponding to i, are new and i, but the access time i is the increment or decrement the value.

Summary **:
** L const is used to define the constants, functions and constants usually defined
variables l let {} are used to define the scope of the block-level variables, typically used to define a loop for
the constant block-level scope is, like use let, the statement defined variables, constants values can not be reassigned to change, and can not be re-statement. ****

## ** Fourth, the deconstruction variable assignment **

4.1 ** ** deconstruction array
arrays can be deconstructed, when the right side of the equal sign is the array, is equal to the left may be loaded into the variable [] is received, the received correspondence.

var [a,b,c] = [1,2,3];
console.log(a); //1
console.log(b); //2
console.log(c); //3

Represents the above code, can, in a corresponding position, variables are assigned values extracted from the array.
In essence, such an approach in "pattern matching", as long as the same pattern on both sides of the equal sign, the variable on the left will be given corresponding values.

If the array is more complicated, this time those variables on the left side of the structure, also have the same structure:

var [a,b,[c,d]] = [1,2,[3,4]];
console.log(a); //1
console.log(b); //2
console.log(c); //3
console.log(d); //4

If the structure is different?

var [a,b,c] = [1,2,[3,4]];
console.log(a); //1
console.log(b); //2
console.log(c); //[3,4]

Another is incomplete deconstruction, namely the equal sign to the left of the mode, only matching part of an array of right-hand side, this deconstruction can still succeed.

var [A, [B], D] = [. 1, [2,. 3],. 4];
the console.log (A); //. 1
the console.log (B); // 2
the console.log (D); 4 //
If successful deconstruction, the value of the variable is equal to undefined

4.2 ** ** deconstruction objects
objects have different structures and array of points, elements of the array are arranged in order, the array is determined by the value of his position.
The property (keys) objects no order, but must attribute variable of the same name, in order to get the correct value.

var {name,id,sex} = {"id":1001,"name":"张三","sex":"男"};
console.log(id); //1001
console.log(name); //张三
console.log(sex); //男

Examples of the above order of variables and three to the left operand of the order of the right hand side of the same name attribute is inconsistent, but absolutely no influence on the value of
the same name attribute if the corresponding variable is not, fail to result in value, it is undefined.
If the variable and attribute names are inconsistent, we must be written as follows:

the foo {var: baz} = {the foo: ', aaa',, bar: ', bbb',}
console.log (baz); // aaa


var {first :f ,last :l} = {first :'hello', last :'world'}
console.log(f); //hello
console.log(l) //world

This is actually stated deconstruction assignment object is shorthand form of the above
the above code, foo is a matching pattern, baz is variable, the variable is assigned a real baz, rather than the pattern foo.
Is to say, the internal mechanism of deconstruction object is to find the same name Properties, and then assigned to the variable corresponding to the real assignment was the latter, and not the former.

** 4.3 ** defaults
structure assignment allows you to specify a default value

var [a = 1] = []
var [b = 1] = [88]
console.log(a);//1
console.log(b);//88
var [c = 1] = [undefined]
var [d = 1] = [null]
console.log(c);//1
console.log(d);//null

Note, ES6 internal use strict equality operator (===), to determine whether there is a position value, so only when strictly equal member of an array undefined, the default values will take effect
if an array value is null, the default value will not take effect because null is not strictly equal undefined.

** 4.4 Extended operator (spread operator) **
Extended operator (Spread) is three dots (...). The array into a sequence of parameters separated by commas, but also forced to expand an object, usually for assignment objects, flexible wide.

The first effect of l: called "Expand operator", and a letter means for acting, what is to expand, and can be used in an array of objects.

var obj1 = {
"a" :100,
"b" :200,
"c" :300,
}
var obj2 = {
...obj1,
"d" :888
}
console.log(obj1)
console.log(obj2)
console.log(obj1 === obj2);


Arrays can also force deployed, the assignment is usually an array, such as two arrays into one array:

The remaining 4.5 ** operator (operator REST) **
L Second, three roles: called "residual operator" is a deconstruction, meaning the remaining parameters in an array and assigned to it. General for array or object.

var [a,b,...c] = [1,2,3,4,5,6];
console.log(a);//1
console.log(b);//2
console.log(c);//[3,4,5,6]

Note that "..." The last parameter can only occur through this example and found ... scattered values can be admitted to the array.
Logically, "..." it is an operator. "..." you can break up into scattered array of value.

l supplementary knowledge points, when an object in the key and the value ES6 consistent value may be omitted.

** 2 l Scenario: **
after receiving a large probability function is a parameter when JSON, deconstruction and grammar to write ES6 with formal parameters.
Call functions pass parameters typically k: v, v is omitted

var name = "Bob";
var height = 170.;
var weight = 100;

function mm ({height, name, weight}) {
the console.log ( "Name is:" + name)
the console.log ( "Height:" height +)
the console.log ( "weight is:" + weight)
};

// mm({name:name,"height":height,"weight":weight})
mm({name,height,weight})

The red part of the statement is to create JSON, green part is making structure.
When you call the function parameter order does not affect the structure upset, because deconstruction, will automatically match the key.
()
** L Expand difference operator and the remaining operations operator **
difference between the linear operator deployed on the remaining operators, simply, to some extent, the remaining operators and operators to expand the contrary, expand operator will "expand" into a plurality of array elements, the operator collects the remaining elements, and a plurality of "compressed" into a single element.

4.6 ** ** objects deconstruction Translation
Note: babel will "[]" and "{}" deconstruction becomes one of var.
But not translate babel "Object deconstruction", only translations array deconstruction.
Reason: object-rest-spread further stage in the stage (an experimental properties).
Solution: Install the plug-babel transform-rest-spread, put .babelrc configuration file, you can use.

{
"Presets": [ "ES2015", "es2016"],
"plugins": [ "Object-Transform-Spread-REST"]
}
.babelrc of presets is used to define a preset, plugins defined plug.
Installation depends:
CNPM the install-plugin Babel-Transform-Spread-Object-REST

**

## Fifth, the array method

**
ES6 in an array of four new "King Kong" function: forEach (), map () , filter (), reduce (), are some syntax sugar. forEach () syntax is es5
** 5.1 forEach () iterate **
forEach () method is used to loop through the array, the method callback function receives three parameters
of an array contents is traversed (Item); 2 is an array index (index) corresponding to the array itself is third (array).

var arr = [ "whiteboard", "unitary chicken", "in the red", "rich", "three cake"];
arr.forEach (function (Item, index, Array) {
the console.log (Item, index, Array )
});
Note: forEach () does not return a return value.

** 5.2 map () map **
action map method is easy to understand, "mapping" is the original array is "mapped" into a new array corresponding.

ARR = var [10,20,30,40,50,99];
var = newArr arr.map (function (Item, index, Array) {
return * Item 2; // return a new result to the variable reception, invariant source array
});

the nature of the map function is, traversing each of the original array, each of which will survive a function in the statement returns a new array.
Note:
L function return value is needed, if not, all the array are mapped into undefined.
l map array and the return of a certain length as the original array.
l
in practical use can be utilized map () to facilitate access to the object in the array have a particular attribute value
** 5.3 filter () ** filtration
filter to "filter, Filter," meaning, refers to certain post-filter array of the original items, after the new array is returned filtering, usage and map similar.
For example, want from the original array, pick all even, returns a new array.

var arr = [312,55,77,11,13,15,18,26,30,40,50,99];
var newArr = arr.filter(function(item,index,array){
return item % 2 == 0;
});
console.log(arr)
console.log(newArr)

Description: Execute function on each item in turn will arr of, filter callback function needs to return a Boolean value of true or false. true value will be placed in the new array, false ruthlessly abandon you ...
the same point l filter and map: Each one will iterate
l filter and map different point: map returns an array of no less items, filter entries may be less .

** 5.4 reduce () iteration **

arr.reduce (callback [, initialValue])
of a callback parameter of the callback function has four parameters, the initial values of the second set (optional).
callback function has four parameters:
Previous: The last time the result of superposition or initial value of
current: the current item will be involved superimposed
index: the current index value of the
array: the original array itself


seeking the maximum [] array of classic interview:
var arr = [43,5,4,6,4567,78,8,69,568];
// max var = Math.max.apply (null, ARR);
// the console.log (max)

var arr.reduce = max ( function (PREV, CUR) {
the console.log (PREV) // 43,43,43,43,4567,4567,4567 ...
? return PREV> CUR PREV: CUR;
});
the console.log (max); // 4567

reduce the mechanism: traversing the index of the item 1, the value of each will be used as return values prev next traversal, the traversal CUR this time, the accumulated prev kind feeling.
reduce can set the initial parameters (custom), when the second parameter reduce, first traversing reduce this time traversing from 0, 1 item starts instead.

** 5.5 Array uses - write pure functions **
The above four "King Kong" map, filter, reduce particularly useful to do "functional" programming.
What is a pure function?
Refers to a pure function does not depend on the state variable does not change outside of the scope of functions.
l This function does not change the internal parameters passed.
l This function must have passed parameters, a determination will return a value.
l statements in a function, there is not random, such as Math.random (), new Date () , passing the same parameters, the return value must be the same;
l function which can not have any asynchronous statement, such as $ .get ( ), fs.readFile (), setInterval ( )

** l [example 1] Please write the addItem a pure function (), receiving arr, as the n-parameter, it is possible to increase the tail arr n. **

ARR = var [99,77,66];
function the addItem (ARR, n-) {
return [ARR ..., n-];
}
var = arr2 is the addItem (ARR, 88); // Returns a new array
console.log ( arr); // original array unchanged
console.log (arr2);


[Example 4] ** Please write a pure function changeItem, accepts arr, n, A as parameters, can be arr first subscript n items that change the value of a. **

var arr = [ "whiteboard", "unitary chicken", "two", "thirty thousand"];
function changeItem (ARR, n-, A) {
return arr.map ((Item, index) => n-index ==? A: Item)
}
var = arr2 is changeItem (ARR, 2, "nine");
the console.log (ARR);
the console.log (arr2 is);


** Conditions l pure function: **
l a function returns the result depends only on its parameters
l does not depend on external state
l implementation process without side effects

** What is the execution of the function has no side effects? **
during the execution of a function in a number of externally generated, then the function is said to have side effects.

l Change the id attribute specifies the name of

const changeName = function(arr,id,name){
return arr.map(function(item){
if(item.id == id){
return {...item,name}
}
return item;
});
}

 

var jieguo = changeName (arr, 2 , " Betty")
the console.log (jieguo);

jingle: delete filter, change map, map or by ...

** summary
Why build a pure function pains? Because pure function very "tricky" to perform a pure function you need not worry it will do bad things, it does not produce unpredictable behavior, it does not have an impact on the outside. No matter when and where, you spit out what it will obediently give it anything. If your application most functions are composed of pure function, then your program testing, debugging, it will be very convenient.
l benefits of using pure function of
the most important benefit is no side effects. Pure function does not modify state outside of the scope, to do this, the code becomes simple and clear enough: when you call a pure function, as long as you pay attention to it the return value, but do not worry because of problems elsewhere results in an error .

Pure functions are robust to change the order of execution does not affect the system, and therefore the operation may be performed in parallel pure function.
Pure function unit test is easy, it is not necessary to consider context, need only consider the input and output.

Function is to accept a number of inputs and produces some of the process output. These input parameters is called, the return value called the output.
The return value of the function parameter determination pure when it is called by only, it does not depend on the execution state of the system (for example: when, where, call it). **

 

Guess you like

Origin www.cnblogs.com/wjs593/p/10993660.html