Learning record (day02-Es6 template string, deconstruction assignment, arrow function, data structure, for..of traversal, rest parameter, extended operator))

Keywords: Front-end REST Lambda Java Javascript

Day02(Es6 template string, deconstruction assignment, arrow function, data structure, for..of traversal, rest parameter, extension operator)

[TOC]

1.1.1 template string

  • Template string to simplify string patching
//statement
var str = ``;
//Embedded variables
var str = `${variable}`;
			// username + "___" + password
			// `${username} ---- ${password}`           
  • In the template string, you can get the value of the variable through ${variable}.
var username = 'jack';
var age = 18;

console.info(`Your name is ${username} , Your age is ${age}`);

1.1.2 deconstruction assignment

  • ES6 allows you to extract values from arrays and objects and assign values to variables according to certain patterns, which is called destructing.
  • ES5 obtains the syntax of object data as follows:
const people = {
    name: 'lux',
    age: 20
}
const name = people.name;				//ES5 writing
const age = people.age;
console.log(name + ' ‐‐‐ ' + age)
  • Object deconstruction and assignment: resolving multiple attributes to different variables from one object at a time
let {variable 1, variable 2,...} = object;
/ / for example:
	{} = {}
  • The deconstructed variable name must be consistent with the property name.
let student = {
    name : "Zhang San",
    age : 21,
    course : {
        en : 100,
        math : 99
    }
};

let {name,age} = student;
console.info(name + "_" + age);

let {course : {en , math }} = student;
console.info(en + "_" + math );
  • Array deconstruction assignment: assign by array order
let [variable 1, variable 2,...] = array;
/ / for example:
	[] = []
let arr = ['Anhui','Chuzhou'];
let [province,city] = arr;			//arr[0] is assigned to province, and arr[1] is assigned to city.
console.info(province);
console.info(city);

let [pro,cit,cou = 'Quanjiao'] = arr;	//arr[3] if it does not exist, use the default value of 'whole Pepper'
console.info(province);
console.info(city);
console.info(province);
console.info(cou);
  • Common applications: exchange variables
[x, y] = [y, x];
  • Common application: traverse Map
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world
  • Common application: extraction of module content
const { SourceMapConsumer, SourceNode } = require("source-map");

1.1.3 default value of function parameter name

  • Default and Deconstruction
Function function name (parameter name = default){

}
function fun1({x = "x1" , y } = {y : "y2"}){
    return [x , y] ;
}
console.info( fun1() );     //[ 'x1', 'y2' ]
console.info( fun1({}) );   //[ 'x1', undefined ] ,
							//{} override {y:"y2"}, deconstruct default, x=x1,y=undefined
  • Default value application: required parameter
function fun2(args = new Error("Parameter must be filled in")){
    console.info(args);
}

fun2();
fun2("abc");
  • Object shorthand

    //When the property name and the property value (variable) are the same, they can be abbreviated to one. Note: double quotes are not allowed
    //Anonymous function, function keyword can be omitted
    var user = {
    	username,			// "username" : username
    	password,
    	show () {
    
    	}
    }
    

1.1.4 arrow function

  • Arrow function: a concise way to define anonymous functions. (very similar to Lambda expressions in Java)
  • Basic format:
(parameter 1,... () = {
	/ / statement
	Return return value;
}
  • Example:
var fn = function(a,b){         //How ES5 defines anonymous functions
    return a+b;
}

var fn2 = (a,b) =>{             //ES6 arrow function anonymous function
    return a + b;
}
  • If there is only one parameter, parentheses can be omitted
var fn2_1 = () => {
    console.info("No parameters");
}
var fn2_2 = (a) => {
    console.info("One parameter");
}
var fn2_1 = (a,b) => {
    console.info("Multiple parameters");
}
var fn2_3 = a => {              		//Ellipsis
    console.info("One parameter");
}
  • If the body of a function has only one statement, curly braces can be omitted. If this statement is a return statement, return must be omitted.
var fn3_1 = (a,b) => {//Plain sentences
    console.info("Plain sentences");
}
var fn3_2 = (a,b) => {
    return a+b;//return statement
}

var fn3_3 = (a,b) => console.info("Plain sentences");	//Ellipsis of common sentences

var fn3_4 = (a,b) => a+b; //The return statement must be omitted.
  • this object:
  • Arrow function does not have its own this. This of arrow function is not determined when it is called, but when it is defined, its object is this.
  • (in browser environment) that is to say, this of arrow function depends on whether there is function in outer layer. If there is, this of outer layer function is this of inner arrow function. If not, this is window.
var name = "rose";
var person = {
	name : 'jack',
	show : function(){
		console.info( this.name );
	},
	show2 : () => {
		console.info( this.name );
	} 
};

person.show();			//Output jack
person.show2();			//Output undefined, no window object in Node.js, unable to get corresponding value
				//If you want to get jack, you must get it through person.name.

1.2.1 Map data structure (Map set)

  • The Object of JavaScript is essentially a collection of key value pairs (Hash structure), but traditionally only a string can be used as a key. This has brought great restrictions to its use.
  • ES6 provides the Map data structure. It is similar to an object and a collection of key value pairs, but the range of "keys" is not limited to strings.
Establish
new Map();
Setting data
map.set(k,v);
Get data
let v = map.get(k)
Does it exist?
let b = map.has(k)
Delete data
map.delete(k)

1.2.2 Set data structure (Set set)

  • ES6 provides a new Set of data structures. It is similar to an array, but the values of the members are all < U > unique < / u > and there are no duplicate values.
//Set collection: store unique data
 Establish
new Set()
Add data
set.add(val)
  • Filtering duplicate data in an array
var arr = [2, 3, 5, 4, 5, 2, 2];

//Mode 1
var set2 = new Set();
// 1) traverse array and add data to set
arr.map( s => set2.add(s) );
// 2) traverse the set set and add it to the new array
var arr2 = [];
set2.forEach( v => arr2.push(v) );
console.info( arr2 );       //[ 2, 3, 5, 4 ]

//Mode 2
var arr3 = [ ... new Set(arr) ]
console.info( arr3 );       //[ 2, 3, 5, 4 ]

1.3.1 for...of traversal

//Traversing array
for(let a of arr4){       
    console.info(a);
}

//Traverse Map, for... of and deconstruction traverse Map
for(let [k,v] of map4){     
    console.info(`The output data key is ${k}The value is ${v}`);
}

//Traversing Set
for(let s of set4){          
    console.info(s);
}

//The custom object can't be traversed. It needs to be converted into "key array" with the help of keys.
for(let key of Object.keys(obj4)){   	
    console.info(`Object's key is ${key},The value is ${obj4[key]}`);
}

//It can also be converted to "key value pair" with the help of entries.
for(let [k,v] of Object.entries(obj4)){
    console.info(`entries : Object's key is ${k},The value is ${v}`);
}

Existing traversal in JS

Traversal method describe Example
for loop traversal Normal loop, often used to process arrays for (let i = 0;i < array.length;i++){
map() Array chain operation function array.map( fn ).xxx()
forEach() Simplify the traversal of array, Map and Set xxx.forEach( fn )
for...in Traversing enumerable properties of an object in any order for(let xx in obj) {}
for...of Different data structures provide a unified access mechanism for(let xx of obj) {}

1.4.1 rest parameter (parameter...)

  • rest parameter is the variable parameter of JS. Before the last variable in the parameter list, use "..."
Function name(Parameter 1, Parameter 2, ...variable)
function add(...num){               	//The variable parameter num is an array. All the arguments are stored at runtime.
    var sum = 0 ;
        num.forEach( i => sum += i);
    return sum;
}

console.info( add(1,2,3) );

function count(args,...other){
    console.info(arguments.length);     //Although there are parameters, pseudo array, cannot be traversed with forEach
    console.info(other.length);         //The number of variable parameters, true array, can be traversed with forEach
}
count(1,2,3);

1.4.2 extension operators (arguments...)

  • The spread operator is three dots (...). It's like the inverse of the rest parameter.

  • The operation data is an array, which is converted into a comma separated sequence of parameters.

  • The operation data is the object. Take out all traversable properties of the parameter object and copy them to the current object.

  • Extended operator

//Split an object or array completely
...array		--> Multiple elements
...object		--> Multiple attribute pairs

var arr = ['a','b','c'];
function fun3(x,y,z){
    console.info( [x,y,z] );
}

fun3( arr );   //[ [ 'a', 'b', 'c' ], undefined, undefined ]
fun3( ...arr );     //[ 'a', 'b', 'c' ]

let z = { a: 3, b: 4 };
let n = { ...z };				// { a: 3, b: 4 }
  • Apply: merge arrays
var arr1 = ['a', 'b'];

var arr2 = ['c'];

var arr3 = ['d', 'e'];

//Merge with concat function
console.info( arr1.concat(arr2 ,arr3 ) );

//Merge by extension operator
console.info( [...arr1 ,...arr2 ,...arr3] );
  • Applying: String splitting
//Splitting strings with split
console.info( "abc".split("") );

//Split by extension operator
console.info( [..."abc"] );

The summary of daily learning is mainly for the sake of future reading. Of course, if you have any good suggestions, please comment.

Posted by HaZaRd420 on Wed, 16 Oct 2019 06:50:44 -0700