Javascript-es6 practical development tips
This article only lists the relatively practical content in the ES6 development process, not a tall and complete document, if you want to consult the detailed content, you can buy the ES6 books published by Teacher Ruan Yifeng. In addition, ruan Yifeng’s introduction to ECMAScript 6 is available at es6.ruanyifeng.com
Define variables/constants
ES6 added two new let and const commands. Let is used to define variables, and const is used to define constants. Different from the original var command, let and const are block-level scopes, and their valid scope is only within the code block.
//es5
if(1= =1) {var b = 'foo';
}
console.log(b);//foo
//es6
if(1= =1) {let b = 'foo';
}
console.log(b);//undefined
Copy the code
Defining a constant object
const a = {a:1.b:2};
a.b = 3;
console.log(a);//{a:1,b:3}
Copy the code
In the above example, the contents of a constant are still valid after being defined. The reason is that the use of a constant is a pointer to an object, but the contents of the object can still be modified. Note that arrays are also objects. So if you use basic data types when defining constants: string, number, Boolean, etc
const a = 1;
a = 2;// Uncaught TypeError: Assignment to constant variable.
Copy the code
In use, it is recommended to use let and const completely instead of var
Numerical extension
ParseInt – Converts string or Number to integer number. parseFloat – converts string or Number to floating point Number
ParseInt, number. parseFloat has the same function as parseInt and parseFloat. In ES6, Number. The goal is to use code in a way that minimizes global methods and modularizes the language
Test functions
// Tests whether it is an integer
Number.isInteger(21)//true
Number.isInteger(1.11)//false
// Test for NaN
Number.isNaN(Nan)//true
Number.isNaN(1)//false
Copy the code
String extension
String content test
'abcdef'.includes('c');//true
'abcdef'.includes('ye');//false
'abcdef'.startsWith('a');//true
'abcdef'.endsWitch('f');//true
//includes(), startsWith(), endsWith() all support the second parameter,
// The type is numeric, meaning that starting with the NTH character, the second argument to endsWith() is a little different
'abcdef'.includes('c'.4);//false looks for the presence of the 'c' character from the 5th character
'abcdef'.startsWith('d'.3);//true starts at the fourth character to find if it starts with a 'd' character
'abcdef'.endsWith('d'.4);// whether the first four characters of true end in 'd'
Copy the code
The string content is repeated
'a'.repeat(5);//aaaaa is repeated five times
Copy the code
Native support for template languages
//es5
$('#result').append(
'There are <b>' + basket.count + '</b> ' +
'items in your basket, ' +
'<em>' + basket.onSale +
' are on sale! '
);
//es6
// In ES6, a content template can be defined as a wrapped string in which the content remains in its original format
// In addition, you can use the template language directly in the string to fill variables, elegant and concise
$('#result').append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
Copy the code
String traversal output
//for ... The of format is the output of the Iterator in ES6
for(let c of 'abc') {console.log(c);
}
//a
//b
//c
Copy the code
String completion
// Parameter 1: [number] The length of the target string
// Parameter 2: [string] The string to be completed
'12345'.padStart(7.'0')//0012345 - String of less than 7 bits, add target string of insufficient length in the header
'12345'.padEnd(7.'0')//1234500 - String completion at the end
Copy the code
Array extension
Merge array
let a = [1.2];
let b = [3];
let c = [2.4];
let d = [...a, ...b, ...c];//[1, 2, 3, 2, 4] all contents are merged, but the repetition is not removed
Copy the code
Quick conversion to an array
Array.of(3.4.5)/ / / three, four, five
Copy the code
Array content test
// Determine whether the object is an array
if(Array.isArray(obj)){... } [1.2.3].includes(5);//false to retrieve data for 5
// Find the result of the first matching expression. Note that the function returns as long as one item is matched
let a = [1.3.4 -.10].find(function(value, index, arr){
return value < 0;
});
console.log(a);/ / - 4
// Find the result subscript of the first matching expression
let a = [1.3.4 -.10].findIndex(function(value, index, arr){
return value < 0;
});
console.log(a);/ / 2
Copy the code
Content filtering
// exclude negative content
let a = [1.3.4 -.10].filter(function(item){
return item > 0;
});
console.log(a);/ / [1, 3, 10]
Copy the code
The content instance
.keys() – Gets the key names of all elements in the array (actually the subscript index numbers)
.values() – Gets the data for all elements in the array
.entries() – Gets the key names and data of all the data in the array
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
.entries(),.keys(),.values() functions are similar to several functions of the same name in Object, but not practical in actual use. For array operations, you can directly traverse
Object extension
A concise representation of a property
// Use the name of the variable/constant directly as the name of the object property
let a = 'abc';
let b = {a};//{a: 'abc'}
function f(x, y){ return{x, y}; }/ / equivalent
function f(x, y){ return {x: x, y: y}}
let o = {
f(){ return 1; }}/ / equivalent
let o = {
f: function(){ return 1; }}Copy the code
Object content merge
let a = {a:1.b:2}, b = {b:3}, c = {b:4.c:5};
let d = Object.assign(a, b, c);
console.log(d);//{a:1,b:4,c:5}
console.log(a);//{a:1,b:4}
// The above merge method will update the contents of a object at the same time, and the attributes of A will be updated if there are multiple merges.
// Attributes that other objects have will not be added to a;
// Only the first object in the parameter column is affected. The following parameter objects are not modified
// This is the recommended way to merge object data
let a = {a:1.b:2}, b = {b:3}, c = {b:4.c:5};
let d = Object.assign({}, a, b, c);// The first argument adds an empty object, which can be updated at merge time without affecting the actual object variable content
console.log(d);//{a:1,b:4,c:5}// The result is the same as the above method, using this method, the contents of a object is not affected
Copy the code
Object content is merged from the back of the argument order to the front
Object content collection
Object.keys() – Gets all the key names in the Object, returned as an array
var obj = { a:1.b:2 };
var names = Object.keys(obj);//['a', 'b']
Copy the code
Object.values() – Retrieves all the value contents of the Object as an array
var obj = { a:1.b:2 };
var values = Object.values(obj);/ / [1, 2]
Copy the code
Object.entries() – Gets all the member data in an Object and returns it as an array, with its contents as an array
var obj = { a:1.b:2 };
var values = Object.entries(obj);//[['a',1], ['b',2]]
Copy the code
In fact, observing that object.keys (), object.values (), object.entries (), are the same as methods in Java’s MAP, both in terms of method names and usage, helps to understand these functional apis
Object content testing
// Determine whether the object is an array object
if(Object.isArray(someobj)){}
// Check whether the target object is empty
if(someobj && Object.keys(someobj).length)
Copy the code
Deconstruction assignment
let [a, b, c] = [1.2.3];
// Define three variables and assign corresponding values; If the number of values does not match the number of variable names, no corresponding variable value is undefined
let [a, b, c='default'] = [1.2];
// Specify a default value. The default value is specified when a variable is defined. If no content is given, the default value is taken
let[a, b]... = [1.2.3];
// the value of b is [2,3], so that the remaining data can be quickly assigned to the variable,
// In order to avoid ambiguity in code reading, it is not recommended to use this method, just for understanding
let [a,b,c] = 'yes';
console.log(a);//y
console.log(b);//e
console.log(c);//sDestructively assigned strings are assigned as a single characterlet {length}='yes';
console.log(length);/ / 3With object assignment, if the name is a built-in property of the string, the property value is obtainedlet arr = [1.2];
let obj = {a:1.b:2};
function test ({a = 10, b}){
console.log('a:',a);
console.log('b:',b); } test(obj); Destruct a use example of assignment, passing it as a function parameter, and using the default valuesCopy the code
Object structure deconstruction
let obj = {a: 1.b: 2};
let {a, b} = obj;//a=1,b=2Structure assignment using variables requires strict matching of names, and array pattern is strict matching of subscriptslet obj = {a: 1.b: 2};
let {a=0, b=5} = obj; Assign and give default valueslet obj = {a: 1.b: 2};
let {a:A, b} = obj;//A=1,b=2Once you get the content, rename the variablelet obj = {a: 1.b: 2};
let a = 0; ({a, b} = obj); Modify the value of the existing a and generate a new variable Blet obj = {
arr: ['aaa', {a:1}};let {arr:[b, {a}]} = obj;// ArRs here map to each other
console.log(b);
console.log(a); Get the child data of the object and map it to the corresponding variables. Note that the structure should correspondCopy the code
modular
The use scenario for the simplest example
//a.js
let a = {a:1.b:2.c:3};
export default a;
//b.js
import a from 'a.js';// assume that a.js and b.js are in the same directory
console.log(a.a);/ / 1
Copy the code
The above simple example of two script files illustrates the actual use of two files, can be cross-referenced, and obtain the data in the target file; We can think of a script file as a module, so that during the actual development process, business processing content or data processing can be abstracted into a file, and the data can be imported and used by other modules when needed
Arrow function
Basic syntax for arrow functions
(parameter1, the parameter2,... , parameter N) => {function declaration} (parameter1, the parameter2,... , parameter N => expression (single)// equivalent to :(parameter 1, parameter 2... , parameter N) =>{return expression; }
// Parentheses are optional when there is only one argument:(Single argument) => {function declaration} Single argument => {function declaration}// Functions with no arguments should be written in parentheses.() => {function declaration}// The contents of the arrow function cannot be used in constructors, the declared contents, and cannot be used by new an object
Copy the code
Look at a simple example
let count = function(num){
return num + 1;
};
// Use the arrow function to refactor
let count = num= > num + 1;
Copy the code
Function keyword {}, (), and return are no longer required to be written. For simple function bodies, much code can be simplified
let count = num= > {
let base = 50;
let step = 10;
return base + step + 1;
};
Copy the code
Do not omit {} and return keywords when a line of function code cannot be completed
// Multiple entries
let count = (num, step) = > num + step + 1;
// No input parameter
let count = (a)= > 3.1415926;
Copy the code
When there is more than one input parameter or no input parameter, use parentheses to wrap the input parameter
Return an object
// Error, SyntaxError is reported
let count = num= > { base: 50.total: num + 100 };
// Return the object normally
let count = num= > ({ base: 50.total: num + 100 });
Copy the code
context-closedthis
(function(args){function(args){function(args){ }(val)), but not exactly the same, the main difference is the result of this
let goods = {
price: 5.total: function(quantity){
console.log(this.price);// this refers to the goods object
let calc = function(){
return quantity * this.price;// This refers to window
}
returncalc(); }};console.log(goods.total(5));//Nan
Copy the code
The above example could certainly use passing arguments or defining a variable that outside the function to receive the external this(the first sentence inside the function) and using that inside the function to solve the problem, but that is beyond the scope of the current topic
let goods = {
price: 5.total: function(quantity){
console.log(this.price);// this refers to the goods object
let calc = (a)= > quantity * this.price; // This also refers to the goods object
returncalc(); }};console.log(goods.total(5));/ / 25
Copy the code
Summary Arrow functions are characterized by shorter functions and context-closed this, and perhaps the shorter functions are the ones we use most
Full content: github.com/TerryZ/js-d…
Personal original content, reproduced please explain the source