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
if (condition) {
var value = 1;
}
console.log(value);
Copy the code
The code is equivalent to
var value;
if(condition) {
value = 1;
}
console.log(value);
Copy the code
If condition is false, the final condition is undefined.
var tmp = new Date(a);function f() {
console.log(tmp); //undefined
if (false) {
var tmp = "hello world"; }}Copy the code
Because of the variable promotion, the code is equivalent to
var tmp = new Date(a);function f() {
var tmp = 'undefined';
console.log(tmp); //undefined
if (false) {
// If false, it will never be assigned
tmp = "hello world"; }}Copy the code
- Case 2: Variables leak and become global variables
In the for loop:
for (var i = 0; i < 10; i++) {
...
}
console.log(i); / / 10
// I can also be accessed here
Copy the code
We can still access the value of I even after the loop has ended.
To increase control over the life cycle of variables, ECMAScript 6 introduces block-level scopes.
Block-level scopes exist in:
Inside the function block (the area between characters {and})Copy the code
1. Let and const
1, will not be promoted 2, there is a temporary dead zone 3, cannot repeat the declaration, will report an error 4, advocate the declaration before using 5, will not bind to the global propertyCopy the code
if (false) {
let value = 1;
}
// value is always in if fast
console.log(value); // Uncaught ReferenceError: value is not defined
Copy the code
- const
Const is used to limit bindings that cannot change variables.
const data = {
value: 1
}
// No problem
data.value = 2;
data.num = 3;
/ / an error
data = {}; // Uncaught TypeError: Assignment to constant variable.
Copy the code
Temporary dead zone
console.log(typeof value); // Uncaught ReferenceError: value is not defined
let value = 1;
Copy the code
Which means that before the variable declarations, the variable will not ascend, but would enter a temporary dead zone, if the variable temporary dead zone at present, so is unable to access the variable, complains, only when the program execution to the variable declaration, will from the temporary dead zone, and then we can access.
var value = "global";
1 / / examples
(function() {
console.log(value);
let value = 'local'; } ());2 / / examples
{
console.log(value);
const value = 'local';
};
Copy the code
In the previous example, both errors were reported.
Block level scope in the for loop
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = function () {
console.log(i);
};
}
funcs[0] ();/ / 3
Copy the code
A classic interview question:
// The solution
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = (function (i) {
console.log(i);
})(i);
}
funcs[0] ();/ / 3
// The resolution of the appeal takes advantage of the function execution context
Copy the code
Of course we can solve this using our let variable, but const will report an error.
Let’s do another example:
for (let i = 0; i < 3; i++) {
let i = 'abc';
console.log(i);
}
// abc
// abc
// abc
for (var i = 0; i < 3; i++) {
var i = 'abc';
console.log(i);
}
// abc
Copy the code
When we use var, the scope of I is in the scope of the for loop, and both inside and outside point to the same I. When we first loop, ‘ABC’ is assigned to I, and I is compared to 3, we break out of the loop.
However, our LET is a different case. For (let I = 0; let I = 0; i < 3; I++), which creates a hidden scope within parentheses.
/ / pseudo code
(let i = 0) {
funcs[0] = function() {
console.log(i)
};
}
(let i = 1) {
funcs[1] = function() {
console.log(i)
};
}
(let i = 2) {
funcs[2] = function() {
console.log(i)
};
};
Copy the code
Template string
1. Basic Grammar
let message = `Hello World`;
console.log(message);
Copy the code
If you happen to want to use backapostrophes in strings, you can use backslash escapes:
let message = `Hello \` World`;
console.log(message);
Copy the code
It is worth noting that whitespace, indentation, and line breaks are preserved in template strings:
let message = `
<ul>
<li>1</li>
<li>2</li>
</ul>
`;
console.log(message);
Copy the code
Embed variable $
let x = 1, y = 2;
let message = `<ul><li>${x}</li><li>${x + y}</li></ul>`;
console.log(message); // <ul><li>1</li><li>3</li></ul>
Copy the code
It is worth mentioning that template strings support nesting:
let arr = [{value: 1}, {value: 2}];
let message = `
<ul>
${arr.map((item) => {
return `
<li>${item.value}</li>
`
})}
</ul>
`;
console.log(message);
Copy the code
This is because: the map is an array, returns after [” ↵ < li > 1 < / li > ↵ “, “↵ < li > 2 < / li > ↵”]. The value in the ${} braces is converted to a string if it is not a string. For example, an array [1, 2,3] is converted to 1,2,3. This is how commas are generated.
Solutions:
let arr = [{value: 1}, {value: 2}];
let message = `
<ul>
${arr.map((item) => {
return `
<li>${item.value}</li>
`
}).join('')}
</ul>
`;
console.log(message);
Copy the code
2. Label template
let x = 'Hi', y = 'Kevin';
var res = message`${x}, I am ${y}`;
// The function is followed by our argument template
console.log(res);
Copy the code
We define the function
/ / text literals
// Notice that in this example the first and last elements of literals are empty strings
function message(literals, value1, value2) {
console.log(literals); // [ "", ", I am ", "" ]
console.log(value1); // Hi
console.log(value2); // Kevin
}
Copy the code
Put it back together again:
function message(literals, ... values) {
let result = ' ';
for (let i = 0; i < values.length; i++) {
result += literals[i];
result += values[i];
}
result += literals[literals.length - 1];
return result;
}
Copy the code
The label template
Arrow function
1. Basic Grammar
ES6 added arrow functions:
let func = value => value;
Copy the code
Is equivalent to:
let func = function (value) {
return value;
};
Copy the code
If you need to pass more than one argument to a function:
let func = (value, num) => value * num;
Copy the code
If a function block requires more than one statement:
let func = (value, num) => {
return value * num
};
Copy the code
If you need to return an object directly:
let func = (value, num) => ({total: value * num});
Copy the code
Combined with variable deconstruction:
Pass an object and return a new object:
let func = ({value, num}) = > ({total: value * num})
/ / use
var result = func({
value: 10.num: 10
})
console.log(result); // {total: 100}
Copy the code
2. The difference between arrow functions and non-arrow functions
- This binding problem
Arrow functions do not have this, specified by the this of the nearest non-arrow function outside. (Lookup scope) also cannot use call(), apply(),bindThese methods change the direction of thisCopy the code
- There is no
arguments
object
The arrow function does not have its own arguments object, which is not necessarily a bad thing, since the arrow function can access the arguments object of the peripheral function:
function constant() {
return() => arguments[0] } var result = constant(1); console.log(result()); / / 1Copy the code
What if we just want to access the arguments to the arrow function?
You can access parameters either as named parameters or as REST parameters:
letnums = (... nums) => nums;Copy the code
- Cannot be instantiated by new
JavaScript functions have two internal methods: [[Call]] and [[Construct]].
When a function is called from new, the [[Construct]] method is executed to create an instance object, and then the function body is executed to bind this to the instance.
When called directly, the [[Call]] method executes the function body directly.
The arrow function does not have a [[Construct]] method and cannot be used as a constructor. If called from new, an error will be reported.
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
Copy the code
- There is no prototype and no super
Fourth, the Symbol
Symbol is a special, immutable data type that can be used as an identifier for object attributes, representing unique values.
1. Basic Usage:
var sym = Symbol('zzz');
console.log(sym);
var obj = {};
obj[sym] = 'xxxhhh111';
console.log(obj);
console.log(obj.sym);
console.log(obj[sym])
Copy the code
The results are as follows:
2, create a Symbol:
Symbol ([description]) the description is optional
Either of the following forms can be used, but the parameters may be easier to distinguish:
var s1 = Symbol('symbol1');
s1 //Symbol(symbol1);
var s2 = Symbol(a); s2//Symbol();
Copy the code
Because the value returned by the Symbol function is unique, the value returned by the Symbol function is unequal.
/ / no parameters
var s1 = Symbol(a);var s2 = Symbol(a); s1 === s2// false
/ / a parameter
var s1 = Symbol('symbol');
var s2 = Symbol('symbol');
s1 === s2 //false
Copy the code
3. Symbol can be used as attribute names
Since each Symbol value is not equal, it is a good choice as an attribute identifier.
let symbolProp = Symbol(a);var obj = {};
obj[symbolProp] = 'hello Symbol';
/ / or
var obj = {
[symbolProp] : 'hello Symbol';
}
/ / or
var obj = {};
Object.defineProperty(obj,symbolProp,{value : 'hello Symbol'});
Copy the code
Note: Settings and access can only be placed in [].
4, Symbol. For
It can be shared globally, and the first thing to look for is whether the item exists globally. If it exists, it will be returned directly, and if it does not exist, it will be created.
let s1 = Symbol.for("uid");
console.log(s1);// Symbol(uid)
let s2 = Symbol.for("uid");
console.log(s1 == s2); // true
Copy the code
5, Symbol. KeyFor ()
The symbol. keyFor method returns the key of a registered value of Symbol type.
var s1 = Symbol.for('foo');
Symbol.keyFor(s1) //"foo"
var s2 = Symbol('foo');
Symbol.keyFor(s2);//undefiend
Copy the code
6. Get the Symbol attribute from the object
let uid = Symbol('uid')
let obj = {
[uid]: 'uid'
}
console.log(Object.keys(obj)) / / []
console.log(Object.getOwnPropertyNames(obj)) / / []
console.log(Object.getOwnPropertySymbols(obj)) // [Symbol(uid)]
Copy the code
7, some notes of Symbol
- Using typeof, the result is “symbol”
var s = Symbol(a);console.log(typeof s); // "symbol"
Copy the code
- The result of instanceof is false
var s = Symbol(a);console.log(s instanceof Symbol); // false
Copy the code
- The Symbol function can take a string as an argument representing a description of the Symbol instance, mainly to make it easier to distinguish when displayed on the console or converted to a string.
var s1 = Symbol('foo');
console.log(s1); // Symbol(foo)
Copy the code
- If Symbol’s argument is an object, the object’s toString method is called and converted to a string before a Symbol value is generated. Because arguments can only be strings.
const obj = {
toString() {
return 'abc'; }};const sym = Symbol(obj);
console.log(sym); // Symbol(abc)
Copy the code
- The Symbol value cannot be evaluated with other types of values and will report an error. You can’t use things like + -, even string concatenation.
var sym = Symbol('My symbol');
console.log("your symbol is " + sym); // TypeError: can't convert symbol to string
Copy the code
- The Symbol value can be explicitly converted to a string.
var sym = Symbol('My symbol');
console.log(String(sym)); // 'Symbol(My symbol)'
console.log(sym.toString()); // 'Symbol(My symbol)'
Copy the code
- Symbol is the attribute name. This attribute does not appear in for… In, for… Of loop, will not be the Object. The keys (), Object, getOwnPropertyNames (), JSON. The stringify () returns. However, it is not private property, with an Object. GetOwnPropertySymbols method, can get all the Symbol of specified Object attribute names.
var obj = {};
var a = Symbol('a');
var b = Symbol('b');
obj[a] = 'Hello';
obj[b] = 'World';
var objectSymbols = Object.getOwnPropertySymbols(obj);
console.log(objectSymbols);
// [Symbol(a), Symbol(b)]
Copy the code
8, Symbol. ToPrimitive
This is a lot more useful, because when you do a type conversion, the object will try to convert to the original type, which is toPrimitive. This method exists on the prototype of the standard type.
When an object converts a primitive type, valueOf is first called and then toString is called. And these are two methods that you can override.
let a = {
valueOf() {
return0}}Copy the code
Of course, you can override symbol. toPrimitive, which has the highest priority when going to base type.
let a = {
valueOf() {
return 0;
},
toString() {
return '1'; },Symbol.toPrimitive]() {
return 2; }}1 + a / / = > 3
'1' + a / / = > '12'
Copy the code
When a conversion is performed, toPrimitive forces a call to a parameter, which in the specification is called hint. This parameter is one of three values (‘number’, ‘string’, ‘default’).
As the name implies, string returns string, number returns number, default is not specified, default.
function Temperature(degrees) {
this.degrees = degrees;
}
Temperature.prototype[Symbol.toPrimitive] = function(hint) {
console.log('hint is', hint)
};
freezing + 2 // hint is default
freezing / 2 // hint is number
freezing + "333" // hint is default
String(freezing) // hint is string
Copy the code
5. Array extensions
Array.from converts a pseudo-array object or traversable object to a true Array
function fun() {
console.log(arguments);
}
var a = 10;
var o = {};
fun(a, o);
Copy the code
function fun() {
console.log(arguments);
console.log(Array.from(arguments));
}
var a = 10;
var o = {};
fun(a, o);
Copy the code
2, array. of(v1, v2, v3) : converts a series of values to an Array
let items = new Array(2);console.log(items.length) ; / / 2
console.log(items[0]);// undefined
console.log(items[1]);let items = new Array(1.2);console.log(items.length) ; / / 2
console.log(items[0]);/ / 1
console.log(items[1]);/ / 2
Copy the code
Array() takes one numeric argument to indicate the length of the Array, and multiple to indicate a single element.
Array.of() 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
let items = 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]); / / 2
Copy the code
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
Rest Parameters (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.
function addNumbers(a,b,c,d,e){
var numbers = [a,b,c,d,e];
return numbers.reduce((sum,number) = > {
return sum + number;
},0)}console.log(addNumbers(1.2.3.4.5));/ / 15
Copy the code
Written as ES6 instead:
function addNumbers(. numbers){
return numbers.reduce((sum,number) = > {
return sum + number;
},0)}console.log(addNumbers(1.2.3.4.5));/ / 15
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
It can also be used in combination with deconstruction assignment
var array = [1.2.3.4.5.6];
var [a,b,...c] = array;
console.log(a);/ / 1
console.log(b);/ / 2
console.log(c);/ / [3, 4, 5, 6]
Copy the code
Pay attention to
-
Each function can have at most one REST argument and must be at the end. Otherwise, an error will be reported
-
Rest arguments cannot be used in object literal setters
Extend 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.
1, chestnuts,
let values = [25.50.75.100]
// equivalent to console.log(math.max (25,50,75,100));
console.log(Math.max(... values));/ / 100
Copy the code
2. Extension operators can also be used with other arguments
letvalues = [-25,-50,-75,-100] console.log(Math.max(... values,0)); / / 0Copy the code
3. Extended 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
4. Splicing can also be realized
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
Destruct assignment
New to ES6 is deconstruction, which is the process of breaking a data structure into smaller parts.
ES5 is written as follows:
var expense = {
type: "es6".amount:"45"
};
var type = expense.type;
var amount = expense.amount;
console.log(type,amount);
Copy the code
When the data structure is broken down into smaller pieces, extracting the data you want from it becomes much easier using deconstructed assignment.
An appeal chestnut could look like this:
const { type,amount } = expense;
console.log(type,amount);
Copy the code
Here’s an 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.
1. Default values
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
2. Destruct nested objects
let node = {
type: "Identifier".name: "foo".loc: {
start: {
line: 1.column: 1
},
end: {
line: 1.column: 4}}};let { loc: {start, end} } = node;
console.log(start)
console.log(end);
Copy the code
3. Deconstruction is used for parameters
function setCookie(name, value, { secure, path, domain, expires }) {
// Set the cookie code
}
setCookie("type"."js");/ / an error
Copy the code
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 reported
Copy the code
4. Array deconstruction
const names = ["Henry"."Bucky"."Emily"];
const [name1,name2,name3] = names;
console.log(name1,name2,name3);//Henry Bucky Emily
const [name,...rest] = names;// combine with the expansion operator
console.log(rest);//["Bucky", "Emily"]
Copy the code
5. Array length
const {length} = names; console.log(length); / / 3Copy the code
Array destructuring can also be used in assignment contexts, but expressions do not need to be wrapped in parentheses
let colors = ["red"."green"."blue"],
firstColor = "black",
secondColor = "purple";
[firstColor, secondColor] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"
Copy the code
6. Default value
let colors = ["red"];
let [firstColor, secondColor = "green"] = colors;
console.log(firstColor); // "red"console.log(secondColor); //"green"
Copy the code
7. Set this parameter to rest
letArr = [1, 2,3, 5];let a = [...arr];
Copy the code
8. Initialization
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
What is the difference between a Class and a traditional constructor
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 constructor
function MathHandle(x,y){
thisX = x;this. Y = y; } MathHandle.prototype.add =function(a){
return this.x+this. Y; };var m=new MathHandle(1.2);console.log (m. dd ())Copy the code
/ / class syntax
class MathHandle {
constructor(x,y){
thisX = x;this. Y = y; } add(){return this.x+this.y;
}
}
const m=new MathHandle(1.2);
console.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.
- Compare how inheritance is implemented in traditional constructors and ES6 respectively:
// Traditional constructor inheritance
function Animal() {
this.eat = function () {
alert('Animal eat')}}function Dog() {
this.bark = function () {
alert('Dog bark')
}
}
Dog.prototype = new Animal()// Bind the prototype to implement inheritance
var hashiqi = new Dog()
hashiqi.bark()//Dog bark
hashiqi.eat()//Animal eat
Copy the code
/ / ES6 inheritance
class Animal {
constructor(name) {
this.name = name
}
eat() {
alert(this.name + ' eat')}}class Dog extends Animal {
constructor(name) {
super(name) // Extend requires super, which represents the superclass constructor, as in Animal
this.name = name
}
say() {
alert(this.name + ' say')}}const dog = new Dog('Husky')
dog.say()// Husky say
dog.eat()// Husky eat
Copy 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
ES6 series iterators and for of
iterators
An iterator is an object with a next() method. Each call to next() returns a result object with two attributes, value indicating the current value and done indicating whether the traversal is complete.
function createIlter(items){
var i = 0;
return {
next: function() {
var done = i >= items.length; // Whether to end
varvalue = ! done ? items[i] :undefined
i++;
return {
done,
value
}
}
}
}
Copy the code
2, the for of
We implemented a simple iterator:
In addition to iterators, we also need a way to iterate over iterators. ES6 provides for of statements, so let’s use for of to iterate over the iterator object we generated in the previous section:
for (let value of arr) {
console.log(value);
}
Copy the code
Error: Not an iterable. Indicates that our generated ARR object is not iterable. VM585:18 Uncaught TypeError: arr is not iterable
So what is traversable?
In fact, a data structure is said to be “iterable” whenever the Iterator interface is deployed.
ES6 states that the default Iterator interface is deployed in the symbol. Iterator property of data structures, or that a data structure can be considered “iterable” as long as it has the symbol. Iterator property.
/ / the iterator
function createIterator(items) {
var i = 0;
return {
next: function() {
var done = i >= items.length;
varvalue = ! done ? items[i++] :undefined;
return {
done: done,
value: value }; }}; }//
var o = {
"name": "zjj"."age": 12
}
// Implement the Inerator interface
o[Symbol.iterator] = function() {
return createIterator(Object.keys(o));
}
/ / traverse
for(var i of o) {
console.log(i)
}
Copy the code
From this, we can also find that the for of traversal is actually the objectSymbol.iterator
Properties.
3, for of the default traversable object
const colors = ["red"."green"."blue"];
for (let color of colors) {
console.log(color);
}
// red
// green
// blue
Copy the code
Although we don’t have to manually add Symbol. The iterator attribute, or can traverse the success, this is because the default deployment ES6 Symbol. The iterator attribute, of course, we can also manually modify this property:
var colors = ["red"."green"."blue"];
colors[Symbol.iterator] = function() {
return createIterator([1.2.3]);
};
for (let color of colors) {
console.log(color);
}
/ / 1
/ / 2
/ / 3
Copy the code
In addition to arrays, some data structures deploy the symbol.iterator property by default.
So the for… The scope of the OF loop includes:
- An array of
- Set
- Map
- Class array objects, such as arguments objects, DOM NodeList objects
- The Generator object
- string
4. Iterator interface
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).
- Several cycles
How do I elegantly improve the for loop in my program