Table of contents
1.es6: Destructuring assignment
7. Optional chaining operator in ES6
9. Use of asynchronous function await
10. There are a large number of selected branches, requiring too many if judgments
13. Convert Object property into property array
15. Filter out values in the array
1.es6: Destructuring assignment
const obj = {
a:1,
b:2,
c:3,
d:4,
e:5,
}
es6:
const {a,b,c,d,e} = obj;
const f = a + d;
const g = c + e;
If the variable name you want to create is inconsistent with the property name of the object
const {a:a1} = obj;
console.log(a1);// 1
Supplement: The object of the es6 structure cannot be undefined or null, otherwise an error will be reported
const {a,b,c,d,e} = obj || {};
2. Spread operator
const a = [1,2,3];
const b = [1,5,6];
const c = [...new Set([...a,...b])];//[1,2,3,5,6]
const obj1 = {
a:1,
}
const obj2 = {
b:1,
}
const obj = {...obj1,...obj2};//{a:1,b:1}
3. String concatenation
template string
const name = '小明';
const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;
4. Use includes to judge
Determine whether the specified condition exists in the current array, and return true if it exists after traversing, and return false if it does not exist
const condition = [1,2,3,4];
原本:if(type==1||type==2||type==3||type==4){
}
使用includes:
if( condition.includes(type) ){
//...
}
5. Use find to judge
The find method finds eligible items and will not continue to traverse
const a = [1,2,3,4,5];
const result = a.find(
item =>{ return item === 3 } )
6. obje.values and flat
In the JSON data of a department, the attribute name is the department id, and the attribute value is an array set of department member ids. Now it is necessary to extract all the member ids of the department into an array set.
const deps = {
'采购部':[1,2,3],
'人事部':[5,8,12],
'行政部':[5,14,79],
'运输部':[3,64,105],
}
let member = [];
for (let item in deps){
const value = deps[item];
if(Array.isArray(value)){
member = [...member,...value]
}
}
member = [...new Set(member)]
flat Flatten the array, convert multi-dimensional to one-dimensional array
const HHL = [1, 2, 3, [1, 2, 3, [4, 5]], 6]
HHL.flat(Infinity) infinity infinite no matter how many layers
7. Optional chaining operator in ES6
ES5 writing => const name = obj && obj.name;
if(req && req.data && req.data.params && req.data.params.type === '200'){}
ES6 writing => const name = obj?.name;
if(req?.data?.params?.type === '200'){}
Before optimization: arr &&arr,length>0
After optimization: arr?.length>0
8. Non-null judgment
原本:if(value !== null && value !== undefined && value !== ''){
//...
}
ES6:if((value??'') !== ''){
//...
}
9. Use of asynchronous function await
original:
const fn1 = () =>{
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 300);
});
}
const fn2 = () =>{
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 600);
});
}
const fn = () =>{
fn1().then(res1 =>{
console.log(res1);// 1
fn2().then(res2 =>{
console.log(res2)
})
})
}
Improve:
const fn = async () =>{
const res1 = await fn1();
const res2 = await fn2();
console.log(res1);// 1
console.log(res2);// 2
}
但是要做并发请求时,还是要用到Promise.all()。
const fn = () =>{
Promise.all([fn1(),fn2()]).then(res =>{
console.log(res);// [1,2]
})
}
10. There are a large number of selected branches, requiring too many if judgments
Before optimization:
function chFruit(type='apple'){
if(type ==='apple'){
return '苹果'
}
else if(type ==='pear'){
return '梨'
}
else if(type ==='orange'){
return'橙子'
}
Optimized:
function chFruit(type='apple'){
let fruit={
apple:'苹果',
pear:'梨',
orange:'橙'
}
retrun fruit[type]
}
11. Find the sum, min and max
Use reduce or Math
const array = [1, 2, 3, 4, 5, 6];
array.reduce((a, b) => a + b); // 输出: 21
array.reduce((a, b) => a > b ? a : b) 或 Math.max(...array)//输出6
array.reduce((a, b) => a < b ? a : b); 或 Math.min(...array)// 输出: 1
12. Shuffle the array
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
return Math.random() - 0.5;
});
// 输出
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]
13. Convert Object property into property array
使用Object.entries(),Object.keys()和Object.values()
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj);
// 输出
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3
Object.keys(obj);
(3) ["a", "b", "c"]
Object.values(obj);
(3) [1, 2, 3]
14. Sort
const array = [2, 1, 6, 3, 7, 5];
const objarr=[hhl:"124",hls"1234"]
array.sort((a,b)=>a-b);//升序
array.sort((a,b)=>b-a);//降序
const objectArr = [
{ first_name: 'Lazslo', last_name: 'Jamf' },
{ first_name: 'Pig', last_name: 'Bodine' },
{ first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输出
(3) [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3
15. Filter out values in the array
0,undefined,null,false,"",''可以很容易地通过以下方法省略
const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// 输出
(3) [3, 6, 7]
将十进制转换为二进制或十六进制
const num = 10;
num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"
16. Anti-shake
防抖:
function debounce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
17. Throttling
节流:
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
18. Randomly Sort Arrays
const shuffle = arr => arr.sort(() => 0.5 - Math.random())
在网页上获取选定的文本
const getSelectedText = () => window.getSelection().toString()
计算数组的平均值
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length
reduce
19. Date processing
1.检查日期是否有效
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // true
2.计算两个日期之间的间隔
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2021-11-3"), new Date("2022-2-1")) // 90
3.查找日期位于一年中的第几天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 307
Useful details:
If you know how to use ES6, that’s fine! - Nuggets
33 very practical JavaScript one-line codes, recommended for collection! - Nuggets
56 JavaScript utility functions to help you improve development efficiency! - Nuggets