当前位置:网站首页>[ES6] function parameters, symbol data types, iterators and generators
[ES6] function parameters, symbol data types, iterators and generators
2022-07-25 07:32:00 【Su liang.py】
Author's brief introduction : Su Liang ( Focus on web crawlers , Data analysis , On the way to learning the front end )
Blog home page : Su Liang .py The blog of
Series column :ES6 Basic grammar
Aphorisms : The sea is wide with fish , The sky is high and the birds are flying .
If you think the blogger's article is good , I hope you can support me for the third time in a row !!!
Follow the likes collection
List of articles
Default value settings for function parameters
stay es6 Set the initial value in the default value of the function in , Generally, parameters with default initial values are set , Need to be placed last .
let fun = (a,b,c=15)=>{
return a+b+c;
}
let result = fun(1,2);
console.log(result); //18
Used with deconstruction assignments
info({
name:'suliang',
age:21,
qq_num:'787991021'
})
function info({
name,age,qq_num,address='[email protected]'}){
console.log(name); //suliang
console.log(age); //21
console.log(qq_num) //787991021
console.log(address); //[email protected]
}
rest Parameters
stay es6 Introduced in rest Parameters ( use ...args Express ) Instead of arguments To display arguments .
let fun1 = (...args)=>{
console.log(args);
}
fun1(1,2,3) //(3) [1, 2, 3]
It returns an array object .
Be careful :rest The parameter must be placed at the last .
Extension operator
Extension operator ... You can convert an array into a comma separated sequence of parameters .
let arr = ['xiaohu','gala','ming'];
let fun = (...args) =>{
console.log(args);
}
fun(arr) //(1) [Array(3)]
fun(...arr) //(3) ['xiaohu', 'gala', 'ming']
Application of extension operators
Array merge
let arr1 = ['xiaohu','gala','ming'];
let arr2 = ['wei','breath'];
// Use the extension operator
const RNG = [...arr1,...arr2];
console.log(RNG); //(5) ['xiaohu', 'gala', 'ming', 'wei', 'breath']
// Use the methods in the array
console.log(arr1.concat(arr2)); (5) ['xiaohu', 'gala', 'ming', 'wei', 'breath']
Array copy
let arr = [1,2,3];
let arr_copy = [...arr];
console.log(arr_copy); //(3) [1, 2, 3]
Convert a pseudo array to a real array
In obtaining dom Element time , Usually we get a set of elements , It's actually a pseudo array .
<body>
<p></p>
<p></p>
<p></p>
// 3. Convert a pseudo array to a real array
<script>
let ps = document.querySelectorAll('p');
console.log(ps); //NodeList(3) [p, p, p] Pseudo array
let arr_ps = [...ps];
console.log(arr_ps); //(3) [p, p, p]
</script>
</body>
New data types :symbol
ES6 A new type of raw data is introduced Symbol, Represents a unique value . It is JavaScript The seventh data type of language , Is a data type similar to a string .
Symbol characteristic
- Symbol Is unique , Used to resolve naming conflicts 2) Symbol Value cannot be calculated with other data
- Symbol Defined object properties cannot be used for…in Loop traversal , But you can use
Reflect.ownKeys To get all the key names of the object
symbol The creation of
let s1 = Symbol('su');
let s2 = Symbol('su');
console.log(s1==s2); //false
let s3 = Symbol.for('su');
let s4 = Symbol.for('su');
console.log(s3 == s4); //true
Use symbol Add object properties
let info ={
name:'su',
age:21,
Sayname:function(){
console.log(this.age);
},
[Symbol('sayName')]:function(){
console.log(this.name);
},
[Symbol('sayAge')]:function(){
console.log(this.age);
}
}
const x = Object.getOwnPropertySymbols(info);
info[x[0]](); //su
info[x[1]](); //21
iterator
iterator (lterator) It's an interface , Provide unified access mechanism for different data structures . Any data structure only needs to be deployed lterator Interface , You can complete the traversal operation .
- ES6 Creates a new traversal command
for...ofloop ,lterator Main interface supplyfor...ofconsumption - Original possession iterator Interface data ( You can use
for...ofTraverse )
The following objects are deployed Iterator Interface .
- Array
- Arguments
- Set
- Map
- string
- TypedArray
- NodeList
example :
In the iterator ,for...of The value returned is , and for...in The index is returned .
const arr=['ming','gala','xiaohu'];
for(let x of arr){
console.log(x); //ming,gala,xiaohu
}
Realization principle
- Create a pointer object , Point to the start of the current data structure
- The first time an object is called next Method , The pointer automatically points to the first member of the data structure
- Next, call next Method , The pointer moves all the way back , Point straight to the last member
- Every time you call next Method returns a containing value and done Object of property
Such as :
const arr =['ming','gala','xiaohu'];
// Principle of iterator :
let arr1 = arr[Symbol.iterator]();
console.log(arr1.next()); //{value: 'ming', done: false}
console.log(arr1.next()); //{value: 'gala', done: false}
console.log(arr1.next()); //{value: 'xiaohu', done: false}
console.log(arr1.next()); //{value: undefined, done: true}
Application of iterators : Custom traversal data
example :
// Case a :
let arr = {
name:'su',
info:[21,'787991021','csdn'],
[Symbol.iterator](){
let index = 0;
let _this = this;
return {
next:function(){
if(index < _this.info.length){
const result = {
value:_this.info[index],done:false};
index ++ ;
return result;
}else{
return {
value:undefined,done:true}
};
}
};
}
}
for(let x of arr){
console.log(x);
}
console.log('*****************************');
// Case 2 :
let arr2 = {
num:2,
member:['xiaoming','gala','xiaohu','wei','breath'],
// Custom iterators
[Symbol.iterator](){
let index2 = 0;
return {
next:()=>{
if(index2< this.member.length){
const result2 = {
value:this.member[index2],done:false};
index2 ++;
return result2;
}else{
return {
value:undefined,done:true}
};
}
};
}
};
for(let y of arr2){
console.log(y);
}
Through the principle of iterators, we can customize a wrapper Iterator Interface . You can use for...of Traverse data .
generator
The generator is ES6 A new function control in 、 The scheme used , It gives us more flexibility to control when the function continues to execute 、 Suspend execution, etc .
The generator function is actually ES6 An asynchronous programming solution provided by .
Be careful :
- Generator functions need to be in function Add a symbol after
* - The generator function can be through
yieldKeyword to control the execution process of the function . - The return value of the generator function is a Generator( generator ).
Write a generator function :
function * fun1(){
// adopt yield To control the execution flow of functions
yield console.log('111');
yield console.log('222');
yield console.log('333');
}
let iterator = fun1();
iterator.next(); //111
iterator.next(); //222
iterator.next(); //333
// Traverse
for(let i of fun1()){
console.log(i);
}
Parameters of generator function
- Pass parameters normally
function * fun2 (args){
console.log(args)
yield '111';
yield '222';
yield '333';
}
// Pass parameters normally
let iterator = fun2('AAA');
iterator.next(); //AAA
- stay next Method
stay next Method , Then it will Take this parameter as yield Return value of code block .
function * fun2 (args){
console.log(args)
let num1 = yield '111';
console.log(num1);
let num2 = yield '222';
console.log(num2);
let num3 = yield '333';
console.log(num3);
}
// stay next Method
iterator.next();
iterator.next("BBB"); //BBB
iterator.next('CCC'); //CCC
iterator.next('DDD'); //DDD
Generator function instance
requirement : stay 1 Second output 111,2 Second output 222,3 Second output 333
1. Use timer to realize :
setTimeout(() => {
console.log('111');
setTimeout(() => {
console.log('222');
setTimeout(() => {
console.log('333');
}, 3000);
}, 2000);
}, 1000);
2. Use the generator function to realize
function one (){
setTimeout(() => {
console.log('111');
iterator.next();
}, 1000);
}
function two(){
setTimeout(() => {
console.log('222');
iterator.next();
}, 2000);
}
function three (){
setTimeout(() => {
console.log('333');
iterator.next();
},3000);
}
function * all(){
yield one();
yield two();
yield three();
}
let iterator = all();
iterator.next();
requirement : Simulate and generate user data , Commodity data , Order data
console.log(' Program start execution !');
function users(){
setTimeout(()=>{
let data = ' User data '; // User data is stored here
iterator.next(data);
},1000)
}
function order(){
setTimeout(() =>{
let data = ' Order data '; // Order data is stored here
iterator.next(data);
},1000)
}
function store(){
setTimeout(() => {
let data = ' Commodity data '; // Store commodity data here
iterator.next(data);
}, 1000);
}
function * info(){
let re_users = yield users();
console.log(re_users);
let re_order = yield order();
console.log(re_order);
let re_store = yield store();
console.log(re_store);
}
let iterator = info();
iterator.next();
边栏推荐
- Scavenging vultures or woodpeckers? How to correctly understand short selling
- 华为无线设备STA黑白名单配置命令
- 用VS Code搞Qt6:编译源代码与基本配置
- Use cyclegan to train self-made data sets, popular tutorials, and get started quickly
- New functions of shixizhi are online. These new functions are online in June. Can you use them?
- Beijing internal promotion | Microsoft STCA recruits nlp/ir/dl research interns (remote)
- Kubernetes monitoring component metrics server deployment
- UXDB怎么从日期值中提取时分秒?
- 华为无线设备配置WPA2-802.1X-AES安全策略
- 【论文笔记】Next-ViT: Next Generation Vision Transformer for Efficient Deployment in Realistic Industrial
猜你喜欢

Security compliance, non-stop discounts! High quality travel service, "enjoy the road" for you

用VS Code搞Qt6:编译源代码与基本配置

What if Oracle 19C migration encounters large lob tables?

diagramscene工程难点分析

【Unity入门计划】基本概念-触发器 Trigger

钉钉最新版,怎么清除登录手机号历史记录数据

New tea, start "fighting in groups"

Boiling short drama Jianghu: nine of the ten production teams are shooting, with a head sharing fund of more than 30million, and users are addicted to paying routines

Huawei wireless device configuration wpa2-802.1x-aes security policy

QT learning diary 20 - aircraft war project
随机推荐
[programmer 2 Civil Servant] III. resource collection
10 key points and 5 measures for good project management
Huawei wireless device sta black and white list configuration command
第一启富金怎么样
【刷题笔记】搜索插入位置(二分法的活用)
QT6 with vs Code: compiling source code and basic configuration
2-6.自动化采集
js无法获取headers中Content-Disposition
【程序员2公务员】一、基本认知
Problems in deep learning training and testing: error: the following arguments are required: --dataroot, solution: the configuration method of training files and test files
RPC通信原理与项目技术选型
paddlepaddle 34 调整模型的layer结构与forward流程(实现layer的增删改与forward的修改)
QT learning diary 20 - aircraft war project
Luo min's backwater battle in qudian
曼哈顿距离简介
"Game illustrated book": a memoir dedicated to game players
New functions of shixizhi are online. These new functions are online in June. Can you use them?
What if Oracle 19C migration encounters large lob tables?
[cloud native] the ribbon is no longer used at the bottom of openfeign, which started in 2020.0.x
On the peak night of the 8 Oracle ace gathering, what technology hotspots did you talk about?