preface
ES6 offers many new features, but we don’t use them very often in our actual work. According to the rule of 20, we should devote 80% of our time and energy to studying the 20 percent of core features, which will get twice the result with half the effort. Writing an article is not easy, please give your support and attention! GitHub blog (mind map included)
First, development environment configuration
This section focuses on Babel compiling ES6 syntax and how to implement modularity with WebPack.
1.babel
Why Babel?
ES6 offers a lot of new features, but not all browsers support them perfectly. The following figure shows the compatibility list of ES6 browsers (export is used as an example).
As you can see from the graph above, some browsers are not very ES6 friendly. For ES6 compatibility issues, many teams have developed various parsing and translation tools (such as Babel, JSX, Traceur, etc.) that can convert our ES6 syntax into ES5. It acts as a translator between ES6 and the browser. Babel is a widely used transcoder that converts ES6 code into ES5 code for execution in existing environments.
How do I configure Babel?
· Install Node.js first, run NPM init, · NPM install --save-dev babel-core babel-preset- ES2015 babel-preset-latest · NPM install -g babel-cli ·babel-versionCopy the code
The configuration file for Babel is.babelrc, which is stored in the root directory of the project. This file is used to set transcoding rules and plug-ins. Details are as follows:
{/ /. Babelrc file"presets": ["es2015"."latest"]."plugins": []}Copy the code
Verify that the configuration is successful
/ SRC /index.js · Contents: [1,2,3]. Map (item=>item+1); Run, Babel. / SRC/index. JsCopy the code
The following shows that Babel has been successfully configured
"use strict";
[1, 2, 3].map(function (item) {
return item + 1;
});
Copy the code
2.webpack
Why use WebPack?
Nowadays, many web pages can be regarded as rich applications, they have complex JavaScript code and a lot of dependent packages, mold quick chemical tools came into being, among which Webpack function is powerful and loved by people. Webpack works by treating your project as a whole through a given master file (e.g. Index.js), Webpack will start with this file to find all of your project’s dependent files, process them with loaders, and finally package them into one (or more) browser-aware JavaScript files.
How do I configure WebPack?
, NPM install webpack Babel - loader - save - dev, create and configure webpack. Config. Js / / webpack config. Js file with the package. The json, at the same level configuration · Run NPM startCopy the code
// configure webpack.config.js to resolve module.exports = {entry:'./src/index.js',
output: {
path: __dirname,
filename: './build/bundle.js'
},
module: {
rules: [{
test: /\.js? $/, exclude: /(node_modules)/, loader:'babel-loader'}}}]Copy the code
// Configure scripts in package.json"scripts": {
"start": "webpack"."test": "echo \"Error: no test specified\" && exit 1"
}
Copy the code
Block-level scope
ES5 has only global scope and function scope (for example, we have to wrap code inside functions to limit scope), which causes many problems:
Case 1: The inner variable overwrites the outer variable
var tmp = new Date();
function f() {
console.log(tmp); //undefined
if (false) {
var tmp = "hello world"; }}Copy the code
Case 2: Variables leak and become global variables
var s = 'hello';
for(var i = 0; i < s.length; i++) { console.log(s[i]); } console.log(i); / / 5Copy the code
ES6 provides let and const declarations instead of var declarations. The new declarations support block-level scope denoted by curly braces, which brings some benefits:
In ES5, we need to construct an immediate function expression to ensure that we do not pollute the global scope. In ES6, we could use simpler braces ({}) and use const or let instead of var to achieve the same effect.
2. Closures in the loop body are no longer a problem. In ES5, if a closure is created in the loop body, accessing variables outside the closure will cause problems. In ES6, you can use “let” to avoid problems.
ES6 does not allow variables of the same name to be declared repeatedly with let or const in the same scope. This is helpful in preventing duplicate declared function expressions in different JS libraries.
Array extension
1. Array.from() : Converts a pseudo-array object or traversable object to a true Array
If all the keys of an object are positive integers or zero and have the length attribute, the object is much like an array and is called a pseudo-array. Typical pseudo-arrays have arguments objects for functions, most DOM element sets, and strings.
. <button> Test 1</button> <br> <button> Test 2</button> <br> <br> Test 3</button> <br> <scripttype="text/javascript">
let btns = document.getElementsByTagName("button")
console.log("btns",btns); ForEach (item=>console.log(item)) Uncaught TypeError: btns.forEach is not afunction
</script>
Copy the code
In ES6, the array.from () method is added to provide a clear and unambiguous way to address the need for array.from ().
Array.from(BTNS).foreach (item=>console.log(item)) converts a pseudo-array to an ArrayCopy the code
2.Array.of(v1, v2, v3) : Converts a series of values to an Array
When the new Array() constructor is called, it actually results in some different results depending on the type and number of arguments passed in, for example:
let items = new Array(2) ;
console.log(items.length) ; // 2
console.log(items[0]) ; // undefined
console.log(items[1]) ;
Copy the code
letitems = new Array(1, 2) ; console.log(items.length) ; // 2 console.log(items[0]) ; // 1 console.log(items[1]) ; / / 2Copy the code
When the Array constructor is called with a single numeric parameter, the length property of the Array is set to that parameter. If you call with more than one parameter (whether numeric or not), those parameters also become items of the target array. This behavior of arrays is both confusing and risky, because sometimes you may not pay attention to the type of parameter being passed.
ES6 introduces the array.of () method to solve this problem. This method acts much like the Array constructor, but does not result in special results when using a single numeric parameter. The array.of () method always creates an Array containing all the parameters passed in, regardless of their number or type:
letitems = Array.of(1, 2); console.log(items.length); // 2 console.log(items[0]); // 1 console.log(items[1]); // 2 items = Array.of(2); console.log(items.length); // 1 console.log(items[0]); / / 2Copy the code
Array.of can basically be used as an alternative to Array() or newArray(), and there is no overloading due to different parameters, and their behavior is very uniform.
3. Find () and findIndex() of array instances
The find method of an array instance, used to find the first array member that matches the criteria. Its argument is a callback function that is executed by all array members until the first member that returns true is found, and then returned. If there is no qualified member, undefined is returned.
[1, 4, -5, 10].find((n) => n < 0) // -5
Copy the code
The findIndex method on an array instance is used much like the find method, returning the location of the first qualified array member, or -1 if all members fail.
[1, 5, 10, 15].findIndex(function(value, index, arr) {
returnvalue > 9; / / 2})Copy the code
4. Array instance includes()
The array.prototype. includes method returns a Boolean value indicating whether an Array contains a given value. The second argument to this method represents the starting position of the search, which defaults to 0. If the second argument is negative, it represents the reciprocal position, and if it is greater than the array length (for example, if the second argument is -4, but the array length is 3), it is reset to start at 0.
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(3, -1); // true
[1, 2, 3, 5, 1].includes(1, 2); // true
Copy the code
In the absence of this method, we usually use the indexOf method of arrays to check for the inclusion of a value. The indexOf method has two drawbacks. First, it is not semantic enough. It means to find the first occurrence position of the parameter value, so it is not intuitive enough to compare whether the value is not equal to -1. Second, it uses the strict equality operator (===) internally for judgment, which leads to misjudgment of NaN.
[NaN].indexOf(NaN) // -1
[NaN].includes(NaN) // true
Copy the code
5. Array instance entries(), keys() and values()
ES6 provides entries(), keys() and values() for iterating through groups of numbers. They both return a traverser object, which can be used for… The of loop is traversed, the only differences being that keys() is traversal of key names, values() is traversal of key values, and entries() is traversal of key value pairs.
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
Arrow function
ES6 allows functions to be defined using arrows (=>). It has two main functions: shortening code and changing the this direction, which we’ll cover in more detail:
1. Reduce code
const double1 = function(number){
returnnumber * 2; // const double2 = (number) => {returnnumber * 2; // const double4 = number => number * 2; // Can be further simplifiedCopy the code
Multiple arguments in parentheses
const double6 = (number,number2) => number + number2;
Copy the code
If the arrow function has more than one statement in its code block, enclose them in braces and return them with a return statement.
const double = (number,number2) => {
sum = number + number2
return sum;
}
Copy the code
Because braces are interpreted as blocks of code, if an arrow function returns an object directly, it must enclose braces around the object or an error will be reported.
/ / an errorlet getTempItem = id => { id: id, name: "Temp"}; / / the reportlet getTempItem = id => ({ id: id, name: "Temp" });
Copy the code
Another benefit is simplifying the callback function
[1,2,3].map()function (x) {
returnx * x; }); [1,2,3]. Map (x => x * x); / / [1, 4, 9]Copy the code
2. Change the this pointer
The JavaScript language’s This object has long been a headache, and using this in object methods must be done with great care. The arrow function “bind” this largely solves this problem. Let’s start with an example:
const team = {
members:["Henry"."Elyse"],
teamName:"es6",
teamSummary:function() {return this.members.map(function(member){
return `${member}Affiliated to the${this.teamName}Team `; })}} console.log(team.teamsummary ()); / / /"Henry is on the Undefined team."."Elyse is on the Undefined team."]
Copy the code
The teamSummary function is embedded with another function, which causes the internal this reference to be distorted. How to modify:
Let self = this
const team = {
members:["Henry"."Elyse"],
teamName:"es6",
teamSummary:function() {let self = this;
return this.members.map(function(member){
return `${member}Affiliated to the${self.teamName}Team `; }) } } console.log(team.teamSummary()); / / /"Henry is on the ES6 team."."Elyse is part of the ES6 team."]
Copy the code
Method 2: Bind
const team = {
members:["Henry"."Elyse"],
teamName:"es6",
teamSummary:function() {return this.members.map(function(member){// this does not know where to point toreturn `${member}Affiliated to the${this.teamName}Team `; }.bind(this)) } } console.log(team.teamSummary()); / / /"Henry is on the ES6 team."."Elyse is part of the ES6 team."]
Copy the code
Method 3: Arrow function
const team = {
members:["Henry"."Elyse"],
teamName:"es6",
teamSummary:function() {returnThis.members. Map ((member) => {// this points to the team objectreturn `${member}Affiliated to the${this.teamName}Team `; }) } } console.log(team.teamSummary()); / / /"Henry is on the ES6 team."."Elyse is part of the ES6 team."]
Copy the code
3. Use caution points
(1) The this object inside the function is the object at which it is defined, not the object at which it is used.
(2) Cannot be used as a constructor, that is, cannot use the new command, otherwise an error will be thrown.
(3) You can’t use arguments. This object does not exist in the function body. If you do, use the REST argument instead.
(4) Yield cannot be used, so arrow functions cannot be used as Generator functions.
Rest parameters
ES6 introduces the REST parameter (of the form… Variable name), used to get extra arguments to a function so you don’t need to use the arguments object.
The rest argument goes with a variable that puts the extra arguments into an array. Let’s take an example: how do you implement a summation function?
Traditional writing:
function addNumbers(a,b,c,d,e){
var numbers = [a,b,c,d,e];
return numbers.reduce((sum,number) => {
returnsum + number; }}, 0) console. The log (addNumbers (1, 2, 3, 4, 5)); / / 15Copy the code
ES6 writing:
functionaddNumbers(... numbers){return numbers.reduce((sum,number) => {
returnsum + number; }}, 0) console. The log (addNumbers (1, 2, 3, 4, 5)); / / 15Copy the code
It can also be used in combination with deconstruction assignment
Var array = [6]; var [a,b,...c] = array; console.log(a); //1 console.log(b); //2 console.log(c); / / [3, 4, 5, 6]Copy the code
Rest arguments can also be combined with arrow functions
const numbers = (... nums) => nums; Numbers (1, 2,3,4,5)// [1,2,3,4,5]Copy the code
The rest parameter must be the last parameter in the function.
② Rest arguments cannot be used in object literal setters
let object = {
setname(... Value){// error // perform some logic}}Copy the code
Expansion operators
The one most closely associated with the remaining parameters is the extension operator. Residual parameters allow you to combine multiple independent parameters into an array; The extension operator, on the other hand, allows you to split an array and pass items as separate arguments to a function.
When used in front of a string or array, it is called the extension operator, which I think can be understood as the reverse of the REST parameter, used to unpack an array or string. In some cases, the expansion operator is handy when the function does not allow arrays to be passed in. Here’s an example: the math.max () method, which takes any number of arguments and returns the maximum of them.
let value1 = 25,
letvalue2 = 50; console.log(Math.max(value1, value2)); / / 50Copy the code
But if you want to work with values in an array, how do you find the maximum? The math.max () method does not allow you to pass in an array. Instead, you can add… to the array as you would with the rest argument. And pass it directly to math.max ()
letValues = [25,50,75, 100] // equivalent to console.log(math.max (25,50,75,100)); console.log(Math.max(... values)); / / 100Copy the code
Extended operators can also be mixed with other parameters
letvalues = [-25,-50,-75,-100] console.log(Math.max(... values,0)); / / 0Copy the code
Extension operators unpack strings and arrays
Var array = [1, 2, 3, 4, 5]; console.log(... array); //1 2 3 4 5 var str ="String"; console.log(... str); //S t r i n gCopy the code
Splicing can also be implemented
var defaultColors = ["red"."greed"];
var favoriteColors = ["orange"."yellow"];
var fallColors = ["fire red"."fall orange"];
console.log(["blue"."green". fallColors,... defaultColors,... favoriteColors] //["blue"."green"."fire red"."fall orange"."red"."greed"."orange"."yellow"]
Copy the code
7. Deconstruct assignment —- for more convenient data access
New to ES6 is deconstruction, which is the process of breaking a data structure into smaller parts.
1. Why is deconstruction useful?
In ES5 and earlier versions, getting information from objects or arrays and storing specific data into local variables required a lot of similar code to be written. Such as:
var expense = {
type: "es6",
amount:"45"
};
var type = expense.type;
var amount = expense.amount;
console.log(type,amount);
Copy the code
This code extracts the Type and amount values of the Expense object and stores them in local variables with the same name. While this code looks simple, imagine if you had a large number of variables to deal with and you had to assign them one by one; And if you have a nested data structure that needs to be traversed to find information, you might want to mine the entire structure for a bit of data.
This is why ES6 adds deconstruction to objects and arrays. When a data structure is broken down into smaller pieces, it becomes much easier to extract the data you want from it.
2. The object
In the previous example, object deconstruction makes it easy to get the Type and amount values of the Expense object.
const { type,amount } = expense;
console.log(type,amount);
Copy the code
Let’s look at another example:
let node = {type:"Identifier", name:"foo"},
type = "Literal",name = 5;
({type,name}= node); // Use deconstruction to assign different values console.log(type); // "Identifier"
console.log(name); // "foo"
Copy the code
Note: You must wrap a destruct assignment in parentheses because exposed curly braces are parsed into code block statements, and block statements are not allowed to appear to the left of the assignment operator (i.e., the equal sign). The parentheses indicate that the curly braces inside are not block statements but should be interpreted as expressions, allowing the assignment to complete.
Default: You can optionally define a default value to use if the specified property does not exist. To do this, add an equal sign after the attribute name and specify a default value, like this:
let node = {
type: "Identifier",
name: "foo"
};
let {
type,
name,
value = true
} = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // true
Copy the code
Nested object deconstruction: Using syntax similar to object literals, you can drill down into nested object structures to extract the data you want.
let node = {
type: "Identifier",
name: "foo",
loc: {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 4
}
}
};
let{ loc: { start }} = node; console.log(start.line); // 1 console.log(start.column); / / 1Copy the code
The destructuring pattern in this example uses curly braces to indicate that you should go inside the LOC property of the Node object to find the Start property.
Destruct parameters that must be passed values
function setCookie(name, value, {secure, path, domain, Expires}) {// Set the code for Cookie}setCookie("type"."js"); / / an errorCopy the code
In this function, the name and value parameters are required, but Secure, PATH, Domain, and Expires are not. By default an error is thrown when calling a function without passing a value to the argument. As in the example above, if setCookie does not pass the third parameter, an error is reported. If the deconstruction parameter is optional, you can handle this error by providing default values for the deconstructed parameter.
function setCookie(name, value, {
secure,
path,
domain,
expires
} = {}) {}
setCookie("type"."js"); // No error will be reportedCopy the code
An array of 3.
const names = ["Henry"."Bucky"."Emily"]; const [name1,name2,name3] = names; console.log(name1,name2,name3); //Henry Bucky Emily const [name,...rest] = names; // combine the expansion operator console.log(rest); / / /"Bucky"."Emily"]
Copy the code
Return the number of arrays with {}
const {length} = names; console.log(length); / / 3Copy the code
Array destructuring can also be used in an assignment context, but expressions do not need to be wrapped in parentheses. This is different from the convention of object deconstruction.
let colors = ["red"."green"."blue"],
firstColor = "black",
secondColor = "purple";
[firstColor, secondColor] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"
Copy the code
Default: Array deconstruction assignment also allows you to specify default values anywhere in the array. The default value is used when the item at the specified location does not exist, or its value is undefined.
let colors = ["red"];
let [firstColor, secondColor = "green"] = colors;
console.log(firstColor); // "red"console.log(secondColor); //"green"
Copy the code
With rest parameters
In ES5, the concat() method is often used to clone arrays, for example:
Var colors = ["red"."green"."blue"];
var clonedColors = colors.concat();
console.log(clonedColors); //"[red,green,blue]"
Copy the code
In ES6, you can use the syntax of the remaining items to achieve the same effect
// Clone arrays in ES6let colors = ["red"."green"."blue"];
let [...clonedColors] = colors;
console.log(clonedColors); //[red,green,blue]
Copy the code
Let’s look at an example: How to turn an array into an object
Const points = [[4,5], [10,1], [0,40]]; // The desired data format is as follows. // [ // {x:4,y:5}, // {x:10,y:1}, // {x:0,y:40} // ]let newPoints = points.map(pair => {
const [x,y] = pair;
return{x,y}}) // It is also easier to use the following methodslet newPoints = points.map(([x,y]) => {
return {x,y}
})
console.log(newPoints);
Copy the code
Mixed deconstruction
const people = [
{name:"Henry",age:20},
{name:"Bucky",age:25},
{name:"Emily",age:30} ]; Var age = people[0]. Age; console.log(age); // const [age] = people; console.log(age); // first unpack array {name:"Henry",age:20} const [{age}] = people; // Deconstruct the object console.log(age) again; / / 20Copy the code
4. Pay attention to the point
When destructuring is used to declare variables in conjunction with var, let, and const, an initializer (the value to the right of the equals sign) must be provided. The following code will all throw a syntax error because of the missing initializer:
var { type, name }; // Syntax error!let { type, name }; // Syntax error! const {type, name }; // Syntax error!Copy the code
Template string
Template strings are enhanced strings, identified by backquotes (‘). It can be used as a regular string, it can be used to define multi-line strings, or it can be used to embed variables in strings. The template string contains embedded variables and functions. You need to write the variable name in ${}.
let name = "Henry";
function makeUppercase(word){
return word.toUpperCase();
}
let template =
`
<h1>${makeUppercase('Hello')}.${name}! </h1>// Can store functions and variables <p> Thank you for watching our video, ES6 provides us with a lot of traversal easy to use methods and syntax! </p> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> `; document.getElementById('template').innerHTML = template;
Copy the code
For another example, the ElementUI library is often used at work, and it’s handy to use template strings when customizing a popup:
await this.$alert(` < p > < strong > confirm whether to upgrade ${enclosing lectureName} < / strong > < br > (if existing notes suite, please regenerate after upgrade) < / p > `, {dangerouslyUseHTMLString:true})Copy the code
What is the difference between a Class and a traditional constructor
Conceptually, JS prior to ES6 did not have the same concept of a “class” as other object-oriented languages. For a long time, people used the new keyword to construct objects from functions (also called constructors) as “classes.” Because JS does not support native classes, but only through the prototype to simulate, a variety of simulated classes compared to the traditional object-oriented way is very chaotic, especially when dealing with when the subclass inherits the parent class, the subclass to call the method of the parent class and so on. ES6 provides a more traditional language approach, introducing the concept of classes as templates for objects. With the class keyword, you can define a class. But classes are just syntactic sugar for an object-oriented pattern based on prototypes.
Compare how classes are implemented in traditional constructors and ES6 respectively:
// Traditional constructorfunctionMathHandle (x, y) {this. = x x; This. Y = y; } MathHandle.prototype.add =function() {returnThis. X + this. Y; }; Var m=new MathHandle(1,2); The console. The log (m. dd ())Copy the code
// Class constructor {constructor(x,y){this.x=x; This. Y = y; }add() {returnThis. X + this. Y; }} const m=new MathHandle(1,2); The console. The log (m. dd ())Copy the code
What’s the connection between the two? In fact, the essence of the two is the same, but there are differences in grammatical sugar writing. Syntactic sugar is a syntax added to a computer language that has no effect on the language’s functionality but is easier for programmers to use. For example, class syntax sugar makes the program more concise, more readable.
typeof MathHandle //"function"
MathHandle===MathHandle.prototype.constructor //true
Copy the code
Compare how inheritance is implemented in traditional constructors and ES6 respectively:
// Traditional constructor inheritancefunction Animal() {
this.eat = function () {
alert('Animal eat')}}function Dog() {
this.bark = function () {
alert('Dog bark'}} Dog. Prototype = new Animal() Var hashiqi = new Dog() hashiqi.bark() bark hashiqi.eat()//Animal eatCopy the code
Constructor (constructor) {this.name = name}eat() {
alert(this.name + ' eat'}} class Dog extends Animal {constructor(name) {constructor(name) {super(name); Constructor this. Name = name}say() {
alert(this.name + ' say')
}
}
const dog = new Dog('Husky') dog.say()// Say dog.eat()// Say dog.eatCopy the code
Classes can be inherited using the extends keyword, which is much cleaner and more convenient than ES5’s modified prototype chain.
How does Class differ from a traditional constructor
- Class is syntactically more compatible with object-oriented writing
- Class implementation inheritance is more readable, easier to understand, and friendlier for beginners
- The essence is syntax sugar, use prototype
X. Basic use and principle of 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. Promise is a solution to asynchronous programming that is more reasonable and powerful than traditional solutions (callback functions and events).
Promise in ES6 solved the problem of callback hell, which is when too many asynchronous steps need to be executed step by step, or when there are too many asynchronous operations in a function, resulting in too many nested callbacks, making code too deeply nested to read and maintain. ES6 recognizes this problem and now uses Promise to solve it perfectly.
Principle of Promise
Once the state changes, it never changes again, and you can get this result at any time. There are only two possibilities for the state of the Promise object to change from pending to depressing and from pending to Rejected. The promise object initializes to pending; When resolve is called, it will be fulfilled by pending => depressing; When called reject, it is called pending => Rejected. See the following figure for the specific process:
The use flow of Promise
- New Promise is an instance and a return is required
- The new Promise is passed in as a function that takes resolve reject
- Resolve is executed on success, reject is executed on failure
- Then monitor result
function loadImg(src){
const promise=new Promise(function(resolve, reject) {var img = document. The createElement method ('img') img. Onload =function(){
resolve(img)
}
img.onerror=function() {reject()} img.src= SRC})returnPromise // Returns a promise instance} var SRC ="http://www.imooc.com/static/img/index/logo_new.png"
var result=loadImg(src)
result.then(function(img){console.log(img.width)//resolved callback},function(){
console.log("failed")//rejected(失败)时候的回调函数
})
result.then(function(img){
console.log(img.height)
})
Copy the code
Promise will make code easier to maintain, write asynchronous code like synchronous code, and the business logic easier to understand.
Iterator and for… Of circulation
In ES6, Map and Set are added to JavaScript’s original data structures that represent “collections”, mainly arrays and objects. This requires a unified interface mechanism to handle all the different data structures. An Iterator is one such mechanism. It is an interface that provides a unified access mechanism for various data structures. The Iterator interface can be deployed on any data structure to complete traversal (that is, processing all members of the data structure in turn).
1.Iterator:
- To provide a unified and simple access interface for various data structures;
- Allows the members of a data structure to be arranged in some order
- ES6 created a new traversal command for… The of loop is an Iterator interface for… Of consumption.
2. Data with iterator interface natively (available for traversal)
- Array
- Set the container
- The map container
- String
- The arguments object for the function
- The NodeList object
let arr3 = [1, 2, 'kobe'.true];
for(let i of arr3){
console.log(i); // 1 2 kobe true
}
Copy the code
let str = 'abcd';
for(let item of str){
console.log(item); // a b c d
}
Copy the code
var engines = new Set(["Gecko"."Trident"."Webkit"."Webkit"]);
for (var e of engines) {
console.log(e);
}
// Gecko
// Trident
// Webkit
Copy the code
3. Comparison of several traversal methods
- The for of loop supports not only array traversal, most pseudo-array objects, but also string traversal, as well as Map and Set traversal.
- A for in loop can iterate over strings, objects, and arrays, but not over sets/maps
- ForEach loops cannot iterate over strings, objects, but over sets/maps
Xii. ES6 modularity
ES6, on the level of language standards, implements module functions, and implements them quite simply, aiming to become a common module solution for browsers and servers. Its module functions are mainly composed of two commands: export and import. The export command is used to specify the external interface of a module, and the import command is used to input functions provided by other modules.
Math.js **/ var basicNum = 0; var add =function (a, b) {
return a + b;
};
export{ basicNum, add }; Import {basicNum, add} from'./math';
function test(ele) {
ele.textContent = add(99 + basicNum);
}
Copy the code
As shown in the preceding example, when using the import command, the user needs to know the name of the variable or function to be loaded; otherwise, the command cannot be loaded. To make it easier for users to load the module without reading the documentation, use the export default command to specify the default output for the module.
// export-default.js
export default function () {
console.log('foo');
}
Copy the code
The above code is a module file, export-default.js, whose default output is a function. The import command can specify any name for the anonymous function when the module is loaded by other modules.
// import-default.js
import customName from './export-default';
customName(); // 'foo'
Copy the code
The import command in the above code can point to the methods output by export-default.js with any name, so you do not need to know the function name output by the original module. Note that curly braces are not used after the import command.
If you find this article helpful, you are welcomeMy GitHub blogLike and follow, thank you!