当前位置:网站首页>ES6 notes
ES6 notes
2022-06-30 14:35:00 【tutou_ girl】
Variable deconstruction assignment and default value
Deconstruct assignment
1. What is deconstruction assignment ?
In grammar , Is the function of assignment , Deconstructed as ( A deconstruction on the left . A deconstruction on the right , Enter assignment one by one from left to right )
2. Deconstruct the classification of assignment .

1. The left and right arrays are assigned values for array deconstruction ;2. The left and right objects are assigned values for object deconstruction ;3. On the left is the array , On the right is the string , Assign values to string deconstruction .
4. Boolean value deconstruction is a method of assigning a value to a string .5. Function parameter deconstruction assignment is an application of array deconstruction assignment in function parameters .6. Numeric deconstruction assignment is a kind of string deconstruction assignment .
One 、 brief introduction
1.( Array deconstruction assignment )


result :
2.( Object deconstruction assignment )
( Output results :1 2)
Two 、 The default value is 、 Specific usage methods and application scenarios ( Array deconstruction assignment )
2-1. The default value is ( Array deconstruction assignment )
( Output 1 2 3)
( Output 1 2 undefined)
If the deconstruction assignment is not successfully paired on the deconstruction ( On the left 3 Elements , On the right 2 Elements ,c Pairing value not found ) The default value is undefined, The default value is to solve the problem that the declaration is not assigned .
2-2. Use scenarios ( Array deconstruction assignment )
1. On the exchange of variables
( Output :2 1)
No intermediate variables are needed for storage , Assignment by means of deconstruction , Solve variable exchange
2. Value problem
( Output :1 2)
There is no need to ( The new variable accepts the result , Return by index 0 1 The value of the location )
3. Value problem
( Output :1 4)( Array matching pattern )
The required value can be flexibly extracted .
4.
( Output :1 [2 3 4 5 ])
scene : I don't know the length of the array returned by the function , Take the first one , The rest don't care .
3、 ... and 、 The default value is 、 Specific usage methods and application scenarios ( Object deconstruction assignment )
1. The default value is ( Object deconstruction assignment )
( Output :42 true)
( Output :3 5 )
2. Use scenarios ( Object deconstruction assignment )
1. Front and back end service communication JSON The value of
( Output :abc test)
Arrow function
(1) In function body this object , Is under the scope of the function declaration this, Instead of using the object , Arrowhead function this Direction never changes , Is static .
(2) Can't be used as a constructor , in other words , Not available new command , Otherwise, an error will be thrown .
(3) Not available arguments object , The object does not exist inside the function . If you want to use , It can be used Rest Parameters instead of .
(4) Not available yield command , So the arrow function cannot be used as Generator function .
(5) When there is only one parameter, parentheses can be omitted , Only one sentence of a function statement must omit curly braces , And the function return value is the statement return value .
setTimeOut Of this yes windows, It is Windows Called , In this case, using the arrow function can make this Point to the current function 
Not suitable for use 
rest Parameters
1. This rest And the original arguments There are many similarities , But the results are different ( To get the value of the parameter )
The original way of writing :
----------------------------
function showTeacher(){
console.log(arguments);
}
// The traditional return is an object
showTeacher(' China ','france');
----------------------------
The result returned is an object :
Arguments(2) [" China ", "france", callee: ƒ, Symbol(Symbol.iterator): ƒ]
2. Use this rest The formal expression of :
---------------------------
function demo(...aggs){
console.log(aggs);
}
demo('ajiao',' Cai Lun ');
--------------------------
The result returned is an array :
(2) ["ajiao", " Cai Lun "]
-------------------------
3. If there are multiple parameters, it must be placed at the end , The parameters not included in the following are directly output in the form of array
function demo2(a1,a2,...ag){
console.log(a1);
console.log(a2);
console.log(ag);
}
demo2('one','two','three','four');
The result returned :
one
two
(2) ["three", "four"]
Extension operator …

symbol
What is? Symbol
Symbol By ES6 A new feature introduced by the specification , It is a new basic data type , Its function is similar to a method of identifying uniqueness ID. Usually , We can do it by calling Symbol() Function to create a Symbol example :
let s1 = Symbol()perhaps , You can also call Symbol() Function passes in an optional string parameter , Equivalent to creating for you Symbol An instance is a descriptive information : let s2 = Symbol('another symbol') because Symbol Is a basic data type , So when we use typeof When checking its type , It will return a type of its own symbol, Not something string、object And so on. : typeof s1 // 'symbol' in addition Every Symbol Instances are unique , So when you compare two Symbol At instance time , Will always return false: const a=Symbol("name"); const b=Symbol("name"); console.log(a===b) //false
Application scenarios 1: Use symbol As the object property name
const name=Symbol();
const age=Symbol();
let obj={
[name]:" The code has been "
}
obj[age]=18;
console.log(obj[name]);// The code has been
console.log(obj[age]);//18
also When using the Symbol As an attribute of an object key Cannot use enumeration method after
const name=Symbol();
const age=Symbol();
const obj={
[name]:" The master ",
[age]:16,
sex:" male "
}
console.log(obj)
console.log(Object.keys(obj));//["sex"] Use symbol Properties defined , Enumeration cannot be used to traverse
for(let p in obj){
console.log(p); // sex
}
// Use Object Of API
console.log(Object.getOwnPropertyNames(obj));// ["sex"] Get the attribute name replaced by the symbol type , And is an array
console.log(Object.getOwnPropertySymbols(obj));// [Symbol(), Symbol()]
const sybs=Object.getOwnPropertySymbols(obj);
console.log(sybs[0]===name) //true References will be equal
// Add :
1.Object.getOwnPropertyNames() Method returns the property name of all its own properties of the specified object ( Include non enumerable properties but not Symbol Value as a property of name ) Array of components .
2.Object.getOwnPropertySymbols() Method returns all of a given object itself Symbol Array of properties .
Application scenarios 2: Use Symbol Define the private properties of the class / Method
const Hero=(()=>{
const getRandom=Symbol();
return class Person{
constructor(a,b,c){
this.a=a;
this.b=b;
this.c=c;
}
gongji(){
// const gj=
}
[getRandom](max,min){
return Math.random()*(max-min)+min;
}
}
})()
var per=new Hero(10,20,30,40);
console.log(per); //Person {a: 10, b: 20, c: 30}
// console.log(per[getRandom](10,20)); // Report errors
// This method cannot be called , Because of the present [getRandom] stay Hero On the prototype of
const sybs=Object.getOwnPropertySymbols(Hero.prototype)
console.log(sybs); // So visit Hero The prototype can be called and output to
Symbol Built in attribute values
Symbol.hasInstance: Other objects use instanceof Operator, the internal method pointed to by the property name will be used .
Symbol.isConcatSpreadable: It can be directly defined as an object property or inherited , It is of boolean type . It can control arrays or similar arrays (array-like) The behavior of the object :
1. For array objects , By default , be used for concat when , Will be expanded by array elements and then connected ( Array elements as elements of the new array ). Reset Symbol.isConcatSpreadable You can change the default behavior .
2. For objects like arrays , be used for concat when , The object as a whole is the element of the new array , Reset Symbol.isConcatSpreadable You can change the default behavior .
Symbol.species:species Accessor properties allow subclasses to override the object's default constructor .
Symbol.match: Specifies that the matching is a regular expression instead of a string .String.prototype.match() Method will call this function . This function is also used to identify whether an object has the behavior of a regular expression .
such as , String.prototype.startsWith(),String.prototype.endsWith() and String.prototype.includes()
These methods check whether the first parameter is a regular expression , If it is a regular expression, throw a TypeError. Now? , If match symbol Set to
false( Or a False value ), This means that the object is not intended to be used as a regular expression object .
Symbol.replace: This attribute specifies the method to call when a string replaces the matching string .
Symbol.search: Specified a search method , This method accepts the regular expression entered by the user , Returns the subscript that the regular expression matches in the string , This method is called by the following methods String.prototype.search().
Symbol.split: Point to A method of dividing a string at the index of a regular expression .
Symbol.iterator: A default iterator is defined for each object . The iterator can be for...of Recycling .
Symbol.toPrimitive: It's a built-in Symbol value , It exists as a function value property of an object , When an object is converted to the corresponding original value , This function will be called .
Symbol.toStringTag: It's a built-in symbol, It is usually used as an object's property key , The corresponding property value should be of string type , This string is used to represent the custom type label of the object , Usually only built-in Object.prototype.toString() Method will read the tag and include it in its return value .Symbol.unscopables: Refers to the value used to specify the object , The object itself and inherited from the associated object with Attribute names excluded from environment binding .
Some methods and cases
1.Symbol.for()
Symbol.for(key) According to the given key key, From the runtime symbol Find the corresponding... In the registry symbol, If you find it , Then return it , otherwise , Create a new... Associated with the key symbol, And put it in the overall situation symbol The registry .
Example : Symbol.for("foo"); // Create a symbol And put in symbol The registry , The key is "foo" Symbol.for("foo"); // from symbol The read key in the registry is "foo" Of symbolSymbol.for("bar") === Symbol.for("bar"); // true, It proves the above Symbol("bar") === Symbol("bar"); // false,Symbol() The function returns a new... Every time symbol var sym = Symbol.for("mario"); sym.toString(); // "Symbol(mario)",mario Since symbol stay symbol Key names in the registry , It's time to symbol Its own description string
2.Symbol.keyFor()
Symbol.keyFor(sym) Method to get symbol In the registry with a symbol Associated key .
Example :
// Create a symbol And put in Symbol The registry ,key by "foo"
var globalSym = Symbol.for("foo");
Symbol.keyFor(globalSym); // "foo"
// Create a symbol, But don't put symbol The registry
var localSym = Symbol();
Symbol.keyFor(localSym); // undefined, So we can't find key Of
// well-known symbol We're not here symbol The registry
Symbol.keyFor(Symbol.iterator) // undefined
3.Symbol.toString()
Returns the current symbol The string representation of the object .
symbol The original value cannot be converted to a string , So we can only convert it to its wrapper object first , Call again toString() Method :
Symbol("foo") + "bar";
// TypeError: Can't convert symbol to string
Symbol("foo").toString() + "bar"
// "Symbol(foo)bar", It is equivalent to the following :
Object(Symbol("foo")).toString() + "bar"
// "Symbol(foo)bar"
Example :
Symbol("desc").toString(); // "Symbol(desc)"
// well-known symbols
Symbol.iterator.toString(); // "Symbol(Symbol.iterator)
// global symbols
Symbol.for("foo").toString() // "Symbol(foo)"
4.Symbol.valueOf()
Method returns the current symbol Object contains symbol Original value .
stay JavaScript in , Although most types of objects will automatically and implicitly call their own... Under certain operations valueOf() Methods or toString() Method to convert itself to an original value , but symbol Objects don't do that ,symbol Object cannot be implicitly converted to the corresponding original value :
Object(Symbol("foo")) + "bar";
// TypeError: can't convert symbol object to primitive
// Cannot implicitly call valueOf() Method
Object(Symbol("foo")).valueOf() + "bar";
// TypeError: can't convert symbol to string
// Manual call valueOf() Method , Although converted to the original value , but symbol The original value cannot be converted to a string
Object(Symbol("foo")).toString() + "bar";
// "Symbol(foo)bar", Manual call required toString() The way to do it
边栏推荐
- Experiment 2: stack
- About the problems encountered when using the timer class to stop with a button (why does the QPushButton (for the first time) need to be clicked twice to respond?)
- Problems in QT creator (additional unknown and error lines are listed in the debug output window)
- Laravel configures passport and returns token using JWT
- Laravel upload error
- Lifting scanning tool
- I'd like to ask you, where can I open an account in Foshan? Is it safe to open a mobile account?
- Shell programming overview
- Geoffreyhinton: my 50 years of in-depth study and Research on mental skills
- [kubernetes series] k8s set mysql8 case insensitive
猜你喜欢

"As a service", the inevitable choice of enterprise digital transformation

MySQL back to table query optimization

Upgrade centos7 mysql5.5 to mysql5.7 non RPM in the form of tar package

Initial attack and defense world Misc

How does hbuilder display in columns?

MFQE 2.0: A New Approach for Multi-FrameQuality Enhancement on Compressed Video

PS cutting height 1px, Y-axis tiling background image problem

Why does the folder appear open in another program

Mysql database foundation: stored procedures and functions

Google Earth engine (GEE) -- converts string to number and applies it to time search (ee.date.fromymd)
随机推荐
Chapter 13 signal (III) - example demonstration
Go common lock mutex and rwmutex
Upgrade centos7 mysql5.5 to mysql5.7 non RPM in the form of tar package
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703
Four isolation levels of MySQL
Lifting scanning tool
Go sync. WaitGroup
ot initialized – call ‘refresh’ before invoking lifecycle methods via the context: Root WebApplicati
Notes on reverse learning in the first week of winter vacation
JS to realize simple lottery function
中信期货开户麻烦吗安全吗,期货开户手续费是多少,能优惠吗
[kubernetes series] k8s set mysql8 case insensitive
Go language for loop multivariable use
Ctfshow getting started with the web (ThinkPHP topic)
Notepad regular delete the line of the keyword
[buuctf] [actf2020 freshman competition]include
Dart extended feature
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure
Small exercise of process and signal
The programming competition is coming! B station surrounding, senior members and other good gifts to you!