当前位置:网站首页>ES6 what amazing writing methods have you used
ES6 what amazing writing methods have you used
2022-07-28 13:51:00 【Maic】
es6 Used very much in projects , Browsers also support a lot es6 How to write it , Usually for compatibility , We will use
babelConvert some advanced Syntax , such asArrow function、Promise、Object to deconstructwait , So what do you often use in our project es6[1] Well ?
This article is used by the author according to the summary of previous projects es6, Hope to think and help in the project .
Text begins ...
Define constants / Variable (const/let)
This is a 100% useful , It's a usage that can be used with your eyes closed , But let's note const/let yes es6 The keyword of a block level scope introduced , stay {} Define variables in {} No access from outside , And it doesn't exist The promotion of variables , let And const Variables defined , Cannot be defined repeatedly , use const Declared variables cannot be reassigned .
const STATUS = {
0: ' Not yet begun ',
1: ' Have in hand ',
2: ' It's over '
};
let userName = 'Maic';
object / An array of deconstruction
It will be used very much in the project , Say goodbye to the one-to-one value and then assign value
const userInfo = {
name: 'Maic',
age: 18,
number: 10
}
const {name,age} = userInfo;
console.log(name, age);
const {name: nname, ...rests } = userInfo
console.log(nname, rests): // Maic {age: 18, number: 10}
const url = new URL('https://github.com/type-challenges/type-challenges/issues?q=label%3A5+label%3Aanswer');
const search = url.search;
const [, params] = search.split('?');
console.log(params) // q=label%3A5+label%3Aanswer
const arr = [1,2,3,4];
const [first, ...rest] = arr;
console.log(first, rest); // 1 [2,3,4]
Object dynamic assignment
var key = 'test';
var obj = {
[key]: 'test'
};
Object to merge
const objs = {name: 'Tom', age: 10};
const merge = (target,options) => {
const ret = Object.assign(Object.create({}), target, options);
return ret;
}
const nobj = merge(objs, {age: 18})
// or
const nobj2 = {...objs, age:18};
Array merge
const arr = [1,2,3];
// Copy operation
const narr = [...arr];
// or
const [...n2arr] = arr;
// Merge array
const barr = [4,5,6];
const carr = [...arr,...barr];
Map
Map Also commonly known as collection , You can use this to maintain a set of if Condition judgment of , Or before The strategy pattern A set of data , You can use this to optimize your code , Make business code more extensible , Say goodbye to the redundant if else,switch case, This will be used more , Use the following pseudo code to feel ,
const queryDetail = () => {
console.log('query detail');
};
const queryList = () => {
console.log('query list');
}
const queryPic = () => {
console.log('query pic')
}
const request = new Map([
['getDetail', queryDetail],
['queryList', queryList]
]);
if (request.has('getDetail')) {
request.get('getDetail')();
}
if (!request.has('queryPic')) {
request.set('queryPic', queryPic);
}
// or Loop execution
request.forEach(fn => {
fn();
})
request.get('queryPic')();
console.log(request.entries(request));
// Get all values
console.log(request.values(request));
// Get all key
console.log(request.keys(request));
/*
[Map Entries] {
[ 'getDetail', [Function: queryDetail] ],
[ 'queryList', [Function: queryList] ],
[ 'queryPic', [Function: queryPic] ]
}
*/
Map Common methods
const map = new Map();
Reflect.ownKeys(map.__proto__);
/**
[
0: "constructor"
1: "get"
2: "set"
3: "has"
4: "delete"
5: "clear"
6: "entries"
7: "forEach"
8: "keys"
9: "size"
10: "values"
11: Symbol(Symbol.toStringTag)
12: Symbol(Symbol.iterator)
]
*/
Object turn Map
const obj = {a:1,b:2};
const map = new Map(Object.entries(obj));
/*
Equivalent to
const map = new Map([
['a',1],
['b',2]
]);
*/
console.log(map);// Map(2) { 'a' => 1, 'b' => 2 }
Map Transfer object
var map2 = new Map([['a','123'],['b','234']])
Object.fromEntries(map2.entries()) // {a: '123', b: '234'}
WeakMap
And Map Is the difference between the WeakMap It's a kind of weak quotation ,WeakMap Of key Must be a non basic data type .WeakMap No traversal entries、keys、values、size Method , Only get、set、has、delete Method .
const bodyDom = document.getElementsByTagName('body')[0];
const weakMap = new WeakMap();
weakMap.set(bodyDom, 'bodyDom');
console.log(weakMap.get(bodyDom));
Set
Generally, we often use de duplication operation in projects , Or filter data processing
var newset = [...new Set([1,1,2,3])]
console.log(newset); // 1,2,3
var arrsSet = new Set();
arrsSet.add({name: 'Maic'}).add({name: 'Tom'})
console.log([...arrsSet]);// [ { name: 'Maic' }, { name: 'Tom' } ]
console.log(newset.has(1)) // true
Find the same data in two groups of data according to a certain field , And merge
const data1 = [
{price:100,attr: 'nick'},
{price: 200,attr: ' necktie '}
];
const data2 = [
{price:200,attr: ' glasses '},
{price: 5000,attr: ' Ring '},
{price:100,attr: 'nick'}
];
const findSomeByKey = (target1, target2, key) => {
const target2Set = new Set([...target2]);
const ret = [];
const tagret = target1.map(v => v[key]);
target2.forEach(v => {
Object.entries(v).forEach(s => {
const [, val] = s;
if (tagret.includes(val)) {
const curent = target1.find(v => v[key] === val);
ret.push(v, curent)
}
})
})
return ret
}
findSomeByKey(data1, data2, 'price');
/*
[
{price: 200, attr: ' glasses '},
{price: 200, attr: ' necktie '},
{price: 100, attr: 'nick'},
{price: 100, attr: 'nick'}
]
Set The common method of
const nset = new Set();
console.log(Reflect.ownKeys(nset.__proto__));
/*
[
0: "constructor"
1: "has"
2: "add"
3: "delete"
4: "clear"
5: "entries"
6: "forEach"
7: "size"
8: "values"
9: "keys"
10: Symbol(Symbol.toStringTag)
11: Symbol(Symbol.iterator)
]
*/
WeakSet
No cycle , No, get, Less commonly used
const nweakSet = new WeakSet([['name','Maic'],['age',18]]);
console.log(nweakSet);
console.log(Reflect.ownKeys(nweakSet.__proto__));
/**
"constructor"
1: "delete"
2: "has"
3: "add"
4: Symbol(Symbol.toStringTag)
*/
Reflect
This is a es6 Relatively new in api
// Judge whether the familiar object exists
const nobj = {a: 1}
if ('a' in nobj) {
console.log(' There is ')
} else {
console.log(' non-existent ')
}
// or
console.log(nobj.hasOwnProperty('a'));
// or
console.log(Object.hasOwn(nobj, 'a'))
// now
Reflect.has(nobj, 'a');
// Add properties to the object
Reflect.defineProperty(obj,'b', {value: 22})
console.log(nobj); // {a:1,v:2}
// Delete object properties
Reflect.deleteProperty(nobj, 'a');
console.log(nobj); // {b:22}
// Call function
function f() {
this.age = 18;
this.arg = [...arguments];
console.log(this.arg,this.age); // [1,2] 18
}
Reflect.apply(f, this, [1,2]);
// Equivalent to this in the past
Function.prototype.apply.call(f,this,[1,2])
// All over the object , obtain key
console.log(Reflect.ownKeys(nobj));// ['a', 'b']
Proxy
es6 Object agent , Hijacking object , stay vue3 Realize two-way data binding in , use Proxy Implement an observer mode
var bucket = new Set();
var effect = (fn) => {
bucket.add(fn)
}
const proxyOption = {
set(target, key, val, receiver) {
const result = Reflect.set(target, key, val, receiver);
bucket.forEach(item => {
Reflect.apply(item, this,[])
})
return result
},
get(target, key,receiver) {
return Reflect.get(target, key)
}
}
// Create an observer
const observer = (obj) => new Proxy(obj, proxyOption);
const obj = {
name: 'Maic',
age: 18
}
// take obj Add to the viewer
const userInfo2 = observer(obj);
effect(() => {
console.log(userInfo2.name, userInfo2.age);
});
userInfo2.name = 'Tom'; // Trigger Proxy
async/await
This is used too much , Asynchronous operation becomes synchronous operation ,async A function defined by , Will default to return a Promise, Be careful async There may not be await, But there are await There must be async.
const featchList = () => new Promise((resolve, reject) => {
resolve({code: 0, message: ' success '})
})
const requests = async () => {
try {
const {code} = await featchList();
} catch (error) {
throw error;
}
console.log(code, '=code');
}
requests();
Class
class Utils {
constructor(name, age) {
Object.assign(this, {name, age});
// or
/*
this.name = name;
this.age = age;
*/
}
}
const utils = new Utils('utils', 18)
Function default parameters
function test(name = 'Maic') {
console.log(name)
}
Arrow function
However, note some features of the arrow function , For example, I don't have my own this, Can't be instantiated , You can't use bind,call And so on.
const request = () => {};
// before
const requestFn = function() {}
summary
1、 frequently-used let、const
2、 Object to deconstruct , Extension operator , Array deconstruction, etc
3、Map,Set,Reflect,Proxy、class、 Arrow function And other common applications
4、 An example of this article code example[2]
Reference material
[1]es6: https://es6.ruanyifeng.com/
[2]code example: https://github.com/maicFir/lessonNote/tree/master/javascript/10-es6
边栏推荐
- R language ggplot2 visualization: visualize the scatter diagram and add text labels to the data points in the scatter diagram, using geom of ggrep package_ text_ The rep function avoids overlapping da
- C语言:随机生成数+快速排序
- Remember to use pdfbox once to parse PDF and obtain the key data of PDF
- R语言ggplot2可视化:可视化散点图并为散点图中的数据点添加文本标签、使用ggrepel包的geom_text_repel函数避免数据点标签互相重叠(自定义指定字体类型font family)
- SAP UI5 FileUploader 控件实现本地文件上传,接收服务器端的响应时遇到跨域访问错误的试读版
- 力扣 2354. 优质数对的数目
- C language: random number + quick sort
- Operator3-设计一个operator
- DXF读写:对齐尺寸标注文字居中、上方的位置计算
- 持续(集成-->交付-->部署)
猜你喜欢

持续(集成-->交付-->部署)

Operator3-设计一个operator

不用Swagger,那我用啥?

org.apache.ibatis.exceptions.TooManyResultsException的异常排查过程

Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function

How to play a data mining game entry Edition

The strongest distributed locking tool: redisson

SQL每日一练(牛客新题库)——第4天:高级操作符

Customized template in wechat applet

基于神经网络的帧内预测和变换核选择
随机推荐
POJ1860货币兑换题解
30天刷题计划(三)
Tutorial on the principle and application of database system (060) -- MySQL exercise: operation questions 11-20 (IV)
朋友发来几个面试题
解决跨越的几种方案
Cool operation preheating! Code to achieve small planet effect
Socket类关于TCP字符流编程的理解学习
C语言:优化后的归并排序
【C语言】结构体指针与结构体变量作形参的区别
酷炫操作预热!代码实现小星球特效
Product Manager: job responsibility table
用非递归的方法实现二叉树中的层遍历,先序遍历,中序遍历和后序遍历
LyScript 获取上一条与下一条指令
Rust from introduction to mastery 01 introduction
Debezium系列之:2.0.0.Beta1的重大变化和新特性
记一次使用pdfbox解析pdf,获取pdf的关键数据的工具使用
使用 Fail2ban 保护 Web 服务器免受 DDoS 攻击
掌握闭包,夯实基本功
Facial expression recognition based on pytorch convolution - graduation project "suggestions collection"
R语言因子数据的表格和列联表(交叉表)生成:使用summay函数分析列表查看卡方检验结果判断两个因子变量是否独立(使用卡方检验验证独立性)