Welcome to CSDN blog.csdn.net/m0_46424423
More on ES6 can be found at CSDN blog blog.csdn.net/m0_46424423…
1. An overview of the
- What is the difference between ECMAScript, JavaScript and NodeJs? ECMAScript (ES) is a language standard for loops, judgments, variables, and arrays. ES + Web API = JavaScript NodeJs: A server-side language that uses the ES standard. ES + Node API = JavaScript Both JavaScript and NodeJs are super sets of ES.
- What are the key versions of ECMAScript? Es3.0:1999 ES5.0:2009 ES6.0:2015: From this version, no numbers are used as numbers, but the year ES7.0:2016 is used
- Why is ES6 so important? ES6 solves the language-level problem of JS not being able to develop large applications.
- How to deal with compatibility issues?
2. Block-level binding
2-1 Problems with declaring variables
Use var to declare variables
- Allow duplicate variable declarations: results in data being overwritten
var a = 1; Function print(){console.log(a)} var a = 2; print();Copy the code
- Variable promotion: weird data access, closure issues weird data access
If (math.random () < 0.5) {var a = "ABC "; console.log(a); } else { console.log(a); } console.log(a);Copy the code
closure
var div = document.getElementById("divButtons") for (var i = 1; i <= 10; i++) { var btn = document.createElement("button"); Btn. innerHTML = "button" + I; div.appendChild(btn); btn.onclick = function () { console.log(i); // When the loop ends, I: 11Copy the code
To solve
var div = document.getElementById("divButtons") for (var i = 1; i <= 10; i++) { var btn = document.createElement("button"); Btn. innerHTML = "button" + I; div.appendChild(btn); (function(i){ btn.onclick = function () { console.log(i); // Output 11}})(I)}Copy the code
- Global variables are mounted to global objects: The problem of global object member contamination is that it is easy to overwrite existing members of the window
var abc = "123";
console.log(window.abc);
// var console = "abc";
// console.log(console)
// var name = "abc";
Copy the code
2-2 Declare variables using let
ES6 not only introduced the let keyword to solve the problem of variable declaration, but also introduced the concept of block-level scope: when code executes and braces are encountered, a block-level scope is created, the braces end, and the block-level variable declaration problem is destroyed
- Global variables are mounted to global objects: Global object member contamination problem Let declared variables are not mounted to global objects
let a = 123;
console.log(window.a)
Copy the code
- Duplicate variable declarations allowed: Variables that cause data to be overwritten by let declarations are not allowed to duplicate declarations in the current scope
let a = 123;
let a = 345;
Copy the code
- Allows use in different scopes
let a = 123;
function test(){
let a = 46;
console.log(a);
}
test();
Copy the code
- Variable promotion: Weird data access, closure issues There is no variable promotion with let, therefore, let variables cannot be used before they are defined
console.log(a)
let a = 123;
Copy the code
In the underlying implementation, the variables declared by the let are actually promoted. However, when promoted, they are placed in a “temporary dead zone”. If the variable is in a temporary dead zone, an error is reported: “Cannot access ‘a’ before Initialization”. When the code runs into the declaration of the variable, it is removed from the temporary dead zone. Inside the loop, loop variables declared with let are treated specially, and each time they enter the body of the loop, a new scope is opened and loop variables are bound to that scope (each time a new loop variable is used). Loop variables declared with let in the loop are destroyed at the end of the loop
let div = document.getElementById("divButtons"); for (let i = 1; i <= 10; I ++) {let button = document.createElement("button") button.innerhtml = "button" + I; Button.onclick = function () {console.log(I)} div. AppendChild (button)}Copy the code
Block-level scoping demonstration
let a = 123; // global scope definition a {let a = 456; // Block level scope defines a console.log(a); Log (a) // Variables defined by lets in the block-level scope are not accessible outside the scope. (Inside can use outside, outside can not use inside)Copy the code
demo
If (math.random () < 0.5) {let a = 123; Console.log (a)} console.log(a); console.log(a); console.log(a); console.log(a); console.log(a); console.log(a); console.log(a); // The outside cannot access the insideCopy the code
2-3 Declare variables using const
Const is the same as let in that variables declared only as const must be assigned at declaration time and cannot be reassigned (even to the same value), i.e. constants.
const a = 1;
a = 1;
console.log(a)
Copy the code
In fact, in development, variables should be declared as const as possible to ensure that their values are not tampered with, for the following reasons:
- As a rule of thumb, many variables in development do not change and should not change.
const div = document.getElementById("game"); // In general, div variables do not changeCopy the code
- Many subsequent frameworks or third-party JS libraries require data to be immutable, and using constants ensures this to a certain extent.
Attention to details:
- Constant immutable means that the memory space of the declared constant is immutable. It does not guarantee that other Spaces pointed to by addresses in the memory space are immutable.
const a = { name: "kevin", age: 123 }; a.name = "abc"; Console. log(a) // A cannot be changedCopy the code
- Naming constants 1. Special constants: A constant must be literally immutable, such as PI, the distance between the moon and the earth, or some other configuration that never changes. In general, the name of this constant is all uppercase and multiple words are separated by underscores
Const PI = 3.14; const MOON_EARTH_DISTANCE = 3245563424; // The distance between the moon and earthCopy the code
- Normal constants: use the same names as before
- In a for loop, loop variables cannot use constants; for in loops can use constants
var obj = {
name:"fzq",
age:18
}
for (const prop in obj) {
console.log(prop)
}
Copy the code
3. Strings and regular expressions
3-1 Better Unicode support
In its early days, Unicode used 16-bit binaries to store text because storage space was at a premium. We call a 16-bit binary Code a Code Unit. Later, as a result of technological advances, Unicode expanded the encoding of characters by extending some characters to 32 bits (two symbols) and calling the binary number corresponding to a character a Code Point. To solve this problem, ES6 provides a method for strings: codePointAt, which gets its code points based on the position of the string’s code elements. In addition, ES6 provides a flag: u for the regular expression. If this flag is configured, code points are used to match the regular expression
Const text = "𠮷"; // Console. log(" string length: ", text.length); // Console. log(" string length: ", text.length); //2 console.log(" Use regex test: ", /^.$/.test(text)); / / false regular can't match the console. The log (" using regular testing: "/ ^. $/ u.t est (text)); //true matches console.log(" Get first element: ", text.charcodeat (0)); Console. log(" Get second code: ", text.charcodeat (1)); //𠮷 : \ud842\udfb7 console.log(" Get first codepoint: ", text.codePointat (0)); Console. log(" Get second codepoint: ", text.codePointat (1));Copy the code
Check whether the string char is 32 bits or 16 bits
CodePointAt (I) > 0xFFFF; function is32bit(char, I) {return char. CodePointAt (I) > 0xFFFF; }Copy the code
Gets the true length of a string code point
function getLengthOfCodePoint(str) { var len = 0; for (let i = 0; i < str.length; I ++) {if (is32bit(STR, I)) {if (is32bit(STR, I)) { } len++; } return len; } console.log("𠮷 is 32-bit: ", is32bit("𠮷", 0)) console.log("ab𠮷ab codePoint length: ", getLengthOfCodePoint("ab𠮷ab"))Copy the code
3-2 More string apis
The following are all instances of strings (archetypes). The includes method determines whether the string contains the specified substring. StartsWith Determines whether the string begins with the specified string. It then returns a new string.
Const text = "const text "; Console. log(" does ": ", text.includes(" ")); Console. log(" includes ": ", text.includes(" includes ",3)); // subscript 3 starts to look for console.log(" start with ": ", text.startswith (" start with ")); Console. log(" whether to end with 'ruthless' : ", text.endswith (" ruthless ")); Console. log(" repeat 4 times: ", text.repeat(4));Copy the code
3-3【 extension 】 The symbol of adhesion in regular
Y Y y y y y y y y y y y y y y y y y y
const text = "Hello World!!!" ; const reg = /W\w+/y; Reg. LastIndex = 3; console.log("reg.lastIndex:", reg.lastIndex); console.log(reg.test(text));Copy the code
3-4 Template character string
ES6 previously handled strings in two cumbersome ways:
- Multiline string
Writing a
Var test = "Deng Likes okra \ Deng likes leek ";Copy the code
Write two
Var test = [" dO you like okra ", "do you like leek"]. Join ("\n");Copy the code
Above, multi-line strings are cumbersome to handle
- String splicing
In ES6, template string writing is provided, which can be very convenient for line wrapping and concatenation. All you need to do is change the beginning or end of the string to ‘
Var test = 'Deng Ge likes okra, Deng Ge likes leek';Copy the code
If you want to concatenate js expressions in strings, just use ‘${js expression}’ in the template string.
Var love1 = "okra "; Var love2 = "caraway "; ${1 + 3 * 2/0.5} ${1 + 3 * 2/0.5} ${1 + 3 * 2/0.5} ${1 + 3 * 2/0.5} ${love1 + love2} '} \n\n aubois uses ${JS expression in the template string to interpolate '; console.log(text);Copy the code
3-5 [extension] Template string tag
Var love1 = "okra "; Var love2 = "caraway "; Var text = myTag '${love1}, ${love2}, ${love2} `;Copy the code
The equivalent of
Text = myTag([" myTag ", "myTag "," "] , "okra "," coriander ")Copy the code
Emulates template string functionality
function myTag(parts) { const values = Array.prototype.slice.apply(arguments).slice(1); // parts.length = value.length + 1 let str = ""; for (let i = 0; i < values.length; Parts [I]} : ${values[I]} '; if (i === values.length - 1) { str += parts[i + 1]; } } return str; } console.log(text);Copy the code
String.raw
var text = String.raw`abc\t\nbcd`; // Tell him no special characters, print console.log(text) completely;Copy the code
demo
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <p> <textarea ID =" TXT "></textarea> Multi-line text box <button ID =" BTN "> Set the contents of the div </button> </p> <div id="container"></div> <script> const container = document.getElementById("container"); const txt = document.getElementById("txt"); const btn = document.getElementById("btn"); btn.onclick = function () { container.innerHTML = safe`<p> ${txt.value} <! - here is safe to prevent users from incoming malicious code - > < / p > < h1 > ${TXT. Value} < / h1 > `; } function safe(parts) { const values = Array.prototype.slice.apply(arguments).slice(1); let str = ""; for (let i = 0; i < values.length; i++) { const v = values[i].replace(/</g, "<" ).replace(/>/g, ">" ); str += parts[i] + v; if (i === values.length - 1) { str += parts[i + 1]; } } return str; } </script> </body> </html>Copy the code
conclusion
Before the template string is written, we can add tags:
Tag name 'template string';Copy the code
The tag is a function that takes the following parameters:
- Parameter 1: An array of strings split by interpolation
- Subsequent parameters: all interpolation
4. The function
4-1 Parameter Default value
Let me write it the way I did before
function sum(){
b = b === undefined && 1;
c = c === undefined && 2;
return a+b+c;
}
console.log(sum(10));
Copy the code
When writing a parameter, assign a value to the parameter directly, and the attached value is the default value
This way, when a function is called, the default value will be used automatically if the corresponding argument is not assigned a value (undefined).
function sum(a,b=1,c=2){ return a+b+c; } console.log(sum(10)); Log (sum(10, null,undefined)) console.log(sum(11,null,undefined)); Console. log(sum(1,undefined,5))//1+1+5=7Copy the code
demo
Function getContainer() {console.log(" ABC "); / / ask ABC to run a few times -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 2 times, because the default value is used in two return document. The getElementById (" container "); } /** * Create an element * @param {*} name element name * @param {*} container element parent * @param {*} content element content */ function createElement(name = "div", container = getContainer(), content = "") { const ele = document.createElement(name) if (content) { ele.innerHTML = content; } container.appendChild(ele); } createElement(undefined, undefined)// Call createElement(undefined, undefined, CreateElement (undefined, document.getelementById ("container"), "234242342424") createElement(undefined, document.getelementById ("container"), "234242342424"Copy the code
As long as you add parameter defaults to a function, the function automatically follows the strict mode rule of variables: arguments and parameters are separated
function test(a, b) { console.log("arugments", arguments[0], arguments[1]); // Two parameters 1 2 console.log("a:", a, "b:", b); //1 2 a = 3; console.log("arugments", arguments[0], arguments[1]); // 3 2 console.log("a:", a, "b:", b); // 3 2 } test(1, 2); Function test(a, b=1) {console.log("arugments", arguments[0], arguments[1]); function test(a, b=1) {console.log("arugments", arguments[0], arguments[1]); // Two parameters 1 2 console.log("a:", a, "b:", b); //1 2 a = 3; console.log("arugments", arguments[0], arguments[1]); // 3 2 console.log("a:", a, "b:", b); // 3 2 } test(1, 2);Copy the code
[Extension] Watch out for temporary dead zones
Parameters, like let or const declarations in ES6, are scoped and have temporary dead zones depending on the order in which they are declared.
function test(a, b=a) { console.log(a, b); 1,2} test(1, 2); function test(a, b=a) { console.log(a, b); // Default values: 1,1} test(1); function test(a = b, b) { console.log(a, b); / No parameter Default values: 1,2} test(1, 2); function test(a = b, b) { console.log(a, b); //Cannot access 'b' before initialization } test(undefined, 2);Copy the code
4-2 Remaining parameters
The old method
function sum(args){ let sum = 0; for(let i = 0; i < args.length; i++){ sum += args[i]; } return sum; } console.log(sum([1])); // The array must be passedCopy the code
upgrade
function sum(){ let sum = 0; for(let i = 0; i < arguments.length; i++){ sum += arguments[i]; } return sum; } console.log(sum(1)); // The array must be passedCopy the code
Arguments defects:
- If used with a parameter, it can be confusing
- Semantically, use arguments to get arguments. Missing parameters make it impossible to understand the true purpose of a function from its definition
The remaining parameters of ES6 are specifically used to collect all the trailing parameters and place them into a shape parameter group.
Grammar:
function (... Parameter name){}Copy the code
details
- A function with only one remaining argument
- If a function has a residual argument, the residual argument must be the last argument
Demo 1
function sum(... Args) {//args collects all the parameters in an array let sum = 0; for (let i = 0; i < args.length; i++) { sum += args[i]; } return sum; } console.log(sum()) console.log(sum(1)) console.log(sum(1, 2)) console.log(sum(1, 2, 3))Copy the code
Demo 2
function test(... args1, ... args2) { console.log(args1) console.log(args2) } test(1, 32, 46, 7, 34);Copy the code
Demo 3
function test(a, b, ... args) { } test(1, 32, 46, 7, 34);Copy the code
4-3 Expand operator
Usage:
. Something to unfoldCopy the code
Sum over all the numbers
function sum(... args) { let sum = 0; for (let i = 0; i < args.length; i++) { sum += args[i]; } return sum; }Copy the code
Gets an array of random numbers of a specified length
function getRandomNumbers(length) { const arr = []; for (let i = 0; i < length; i++) { arr.push(Math.random()); } return arr; } const numbers = getRandomNumbers(10); // Sum (numbers) console.log(sum(...) console.log(sum(...)) console.log(sum(...) console.log(sum(... Console. log(sum(1, 3... numbers, 3, 5))Copy the code
Expand array: Clone
const arr1 = [3, 67, 8, 5]; // const arr2 = [0,...arr1, 1]; Const arr2 = [...arr1]; console.log(arr2, arr1 === arr2)//falseCopy the code
Expand object: shallow clone
Const obj1 = {name: "c ", age: 18, love:" D ", address: {country: "C ", province:" D ", city: }} const obj2 = {... Obj1, name: "obj "// obJ can override}; console.log(obj2) console.log(obj1.address === obj2.address)//trueCopy the code
A deep clone
Const obj1 = {name: 1, age: 18, loves: [" 2", address: {country: "3 ", province:" 4 ", city: 1) Const obj1 = {name: 1, age: 18, loves: [" 3 ", province: "4 ", city: 1) }} // Clone to obj2 const obj2 = {... Obj1, name: "obj1 ", address: {//address... Obj1. Address}, loves: [... obj1. Loves "into putting 3"] / / shallow clone}; console.log(obj2) console.log(obj1.loves === obj2.loves) console.log(obj1.address === obj2.address)Copy the code
4-4 Remaining arguments and expansion operator exercises
maxmin
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <div> <p><input type="number" name="" id="" value="0"></p> <p><input type="number" name="" id="" value="0"></p> <p><input type="number" name="" id="" value="0"></p> <p><input type="number" name="" id="" value="0"></p> <p><input type="number" name="" id="" value="0"></p> <p><input type="number" name="" id="" value="0"></p> <p><input type="number" name="" id="" value="0"></p> <p><input type="number" name="" id="" value="0"></p> <p><input type="number" name="" id="" value="0"></p> < p > < input type = "number" name = "" id =" "value =" 0 "> < / p > < / div > < p > < button > computing < / button > < / p > < p > < h2 > maximum: <span id="spanmax"></span></h2> <h2> <span id="spanmin"></span></h2> </p> <script> function getValues() { const numbers = []; const inps = document.querySelectorAll("input") for (let i = 0; i < inps.length; I ++) {numbers. Push (+inps[I].value)// return numbers; } const btn = document.querySelector("button") btn.onclick = function () { const numbers = getValues(); Spanmax. innerText = math.max (... numbers) spanmin.innerText = Math.min(... // Spanmax. innerText = math.max. apply(null,numbers); This binding null} </script> </body> </ HTML >Copy the code
curry
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <script> function cal(a, b, c, d) { return a + b * c - d; } //curry: function curry(func,... Args) {// return function (... SubArgs) {// The new function also doesn't know several const allArgs = [...args,...subArgs]; If (allArgs. Length >= func. Length) {// Return func(... allArgs); } else {return curry(func,... allArgs); } } } const newCal = curry(cal, 1, 2) console.log(newCal(3, 4)) // 1+2*3-4 console.log(newCal(4, 5)) // 1+2*4-5 console.log(newCal(5, 6)) // 1+2*5-6 console.log(newCal(6, 7)) // 1+2*6-7 const newCal2 = newCal(8) console.log(newCal2(9)); // 1+2*8-9 </script> </body> </html>Copy the code
demo
function test(a, b, c) {
console.log(a, b, c);
}
test(2, 6, 7);
const arr = ["asf", "Gfh", "111"];
//以前apply
test(...arr);
Copy the code
4-5 Clarify the dual purpose of functions
4-6 Arrow functions
Review: This points to
- Call a function from an object. This refers to the object
- Call the function directly. This points to the global object
- If the function is called through new, this points to the newly created object
- If the function is called by apply, call, or bind, this points to the specified data
- If it is a DOM event function, this points to the event source