This is the third day of my participation in Gwen Challenge
let&const
Variables declared by var tend to be out of scope, but variables declared by let have strict local scope.
{
var a = 1;
let b = 1;
}
console.log(a); / / 1
console.log(b); //Uncaught ReferenceError: b is not defined
Copy the code
Var can be declared multiple times, let can only be declared once
var a = 1;
let b = 2;
var a = 3;
let b = 4;
console.log(a); / / 3
console.log(b); //Uncaught SyntaxError: Identifier 'b' has already been declared
Copy the code
Var boosts variables, while let does not
console.log(a); //undefined
console.log(b); //Uncaught ReferenceError: Cannot access 'b' before initialization
var a = 1;
let b = 2;
Copy the code
Const declares a constant (read-only variable). It is not allowed to change once declared. It must be initialized, otherwise an error is reported.
const a = 1;
a = 2;
console.log(a); //Uncaught TypeError: Assignment to constant variable.
Copy the code
Destruct expression
An array of deconstruction
// The previous assignment
let arr = ["hello"."world"."ES6"];
let a = arr[0];
let b = arr[1];
let c = arr[2];
console.log(a,b,c); //hello world ES6
/ / after ES6
let [d,e,f] = arr;
console.log(d,e,f); //hello world ES6
let [first] = arr;
console.log(first) //hello
Copy the code
Object to deconstruct
// The previous way
const person = {
name: "java".age: 18.friend: ["python,go,php"]}const name = person.name;
const age = person.age;
const friend = person.friend;
console.log(name, age, friend); //java 18 ["python,go,php"]
// Object destruct
const {name,age,friend} = person;
console.log(name,age,friend); //java 18 ["python,go,php"]
let {name:n, age:a, friend:f} = person;
console.log(n, a, f)
let {name} = person
console.log(name)
Copy the code
String extension
The new API
ES6 extends several new apis for strings:
includes()
: Returns a Boolean value indicating whether the parameter string was found.startsWith()
: Returns a Boolean value indicating whether the parameter string is at the beginning of the original string.endsWith()
: Returns a Boolean value indicating whether the argument string is at the end of the original string.
let a = "hello,world";
console.log(a.startsWith("hello")); //true
console.log(a.endsWith("world")); //true
console.log(a.includes("w")); //true
console.log(a.includes(",")); //true
Copy the code
String template
In addition, there is a string template, which is equivalent to the enhanced string. Backquotes (we’ve been using “” for strings) can be used to define multi-line strings, and variables and expressions can be added to strings.
let name = "Jam";
let age = 18;
function hello(){
return "Hello";
}
let info = I was `${name}Age,${age+1}.${hello()}`;
console.log(info);
Copy the code
Function optimization
Function parameter default value
Before writing
function add(a, b){
b = b || 1;
return a + b;
}
console.log(add(10));
Copy the code
Now you can just give a default value
function add(a, b = 1){
return a + b;
}
console.log(add(10));
Copy the code
Uncertain parameters
The number of indeterminate parameters that must have one and only one indeterminate parameter.
function fun(. values){
console.log(values); // Convert to an array
console.log(values.length); / / 5
}
fun(4.5.6.7.8);
Copy the code
Arrow function
Let me just abbreviate the function
var print = function(obj) {
console.log(obj)
}
/ / short
var print2 = obj= > console.log(obj)
print2("hello")
// Multiple parameters
var sum1 = (a, b) = > a + b;
var sum2 = (a, b) = > {
c = a + b;
return c + 100;
}
console.log(sum1(1.2));
console.log(sum2(1.2));
// If there are no arguments, a placeholder () is required to represent the argument part
let sayhello = () = > console.log("hello")
sayhello()
const person = {
name: "java".age: 18.friend: ["python,go,php"]}// return is omitted
var printName = (person) = > person.name;
console.log(printName(person));
Copy the code
Object new API
const person = {
name: "java".age: 18.friend: ["python,go,php"]}// Combine all attribute names into an array
console.log(Object.keys(person));
// Combine all attribute values into an array
console.log(Object.values(person));
// Take the property name and value separately to form an array
console.log(Object.entries(person));
const target = {
a: 1
};
const source1 = {
b: 2
};
const source2 = {
c: 3
};
// merge source1 and source2 into target
Object.assign(target,source1,source2);
console.log(target);
Copy the code
Declare object shorthand
let person = {
name: "Nginx"./ / before
play: function (things) {
console.log(this.name + ": playing:" + things);
},
// ES6
// Arrow function, can't get this
play2: things= > console.log(person.name + ": playing:" + things),
/ / short
play3(things){
console.log(this.name + ": playing:"+ things); }}; person.play("basketball")
person.play2("game");
person.play3("soccer")
Copy the code
The map method
Receives a function that processes all the elements in the original array and returns them in a new array.
let arr = ["1"."10"."15"."99"];
arr = arr.map(item= > item + "java");
console.log(arr); //["1java", "10java", "15java", "99java"]
Copy the code
Promise
In the JavaScript world, all code is executed in a single thread. Due to this “bug”, all web operations of JavaScript, browser events, must be executed asynchronously. Asynchronous execution can be implemented using callback functions. Once you have a string of Ajax requests A, B, C, D… Subsequent requests depend on the results of previous requests, requiring layers of nesting. This indentation and layers of nested way, very easy to cause confusion, the context code we have to be very careful of dealing with the inner function and outer function data, once the inner function using the upper function variable, the disorder degree will be intensified, the context of the cascade layers of nested way, has increased the nervous tension.
Case: user login, and show the user’s scores. Send the request twice on the page:
-
If the query succeeds, you can log in
-
The user was queried successfully
-
According to the subject query results, to obtain the results
Implementation: First we need to create 3 JSON data according to the requirements
user.json
{
"id": 1,
"name": "zhangsan",
"password": "123456"
}
Copy the code
user_course_1.json
{
"id": 10,
"name": "chinese"
}
Copy the code
course_score_10.json
{
"id": 100,
"score": 90
}
Copy the code
Implement this requirement in the old way
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<script>
// 1. Check the current user information
// select * from user where id = 1
// 3, Select * from course id
$.ajax({
url: "user.json".success(data) {
console.log("Query user:", data);
$.ajax({
url: `user_course_${data.id}.json`.success(data) {
console.log("Query to course:", data);
$.ajax({
url: `course_score_${data.id}.json`.success(data) {
console.log("Query the score:", data);
},
error(error) {
console.log("Something is wrong:"+ error); }}); },error(error) {
console.log("Something is wrong:"+ error); }}); },error(error) {
console.log("Something is wrong:"+ error); }});</script>
</body>
</html>
Copy the code
With Promise encapsulation, there is more code than before, but the logic is clear and desirable.
// Promise encapsulates asynchronous operations
let p = new Promise((success, error) = > {
$.ajax({
url: "user.json".success: function (data) {
console.log("Query user:", data);
// Indicates that the next method, p.teng, is executed after success
success(data);
},
error: function (err) {
console.log("Something is wrong:"+ error); error(err); }}); }); p.then((obj) = > {
// Continue wrapping with promise as there is a third requirement to follow
return new Promise((success, error) = > {
$.ajax({
url: `user_course_${obj.id}.json`.success: function (data) {
console.log("Query to course:", data);
success(data);
},
error: function (err) {
console.log("Something is wrong:" + error);
error(err);
}
})
})
}).then((obj) = > {
$.ajax({
url: `course_score_${obj.id}.json`.success(data) {
console.log("Query the score:", data);
},
error(error) {
console.log("Something is wrong:"+ error); }}); }).catch((err= > {
console.log(err);
}))
Copy the code
Of course, the above code is a lot of, and the actual development we will not do this, let’s go to it as a function.
function get(url) {
return new Promise((success, error) = > {
$.ajax({
url: url,
success: function (data) {
success(data);
},
error: function (err) { error(err); }})}); } get("user.json")
.then((data) = > {
console.log("Query user:", data);
return get(`user_course_${data.id}.json`);
})
.then((data) = > {
console.log("Query to course:", data);
return get(`course_score_${data.id}.json`)
})
.then((data) = > {
console.log("Query the score:", data);
})
.catch((err) = >{
console.log("Something is wrong:" , error);
})
Copy the code
modular
Modularity is the breaking up of code for easy reuse. Similar to guide packages in Java: to use a package, you must lead the package. JS does not have the concept of packages, but instead has modules
The function of the module consists of two commands: export and import.
The export: command is used to specify the external interface of a module. The import: command is used to import functions provided by other modules.
Here’s an example:
Export a function and a variable ->hello.js
const util = {
sum(a, b){
returna+b; }};var name = "java";
// Export the util object
export {util};
// Export the name object
export {name};
Copy the code
Export to use main.js
import {name, util} from "./hello.js";
console.log(name);
util(1.2);
Copy the code