js代码简洁化、ES6方法 笔记

目录

1.es6:解构赋值

2.展开运算符

3.字符串拼接

4.使用includes判断  

5.使用find判断

6.obje.values和flat

7.ES6中的可选链操作符

8.非空判断

9.异步函数await使用

10.有大量选中分支,需要过多if判断

11.找出总和、最小值和最大值

12.打乱数组

13.将Object属性转成属性数组

14.排序

15.数组中过滤出值

16.防抖

17.节流

18.随机排序数组

19.日期处理


1.es6:解构赋值

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;

如果想创建的变量名和对象的属性名不一致
const {a:a1} = obj;
console.log(a1);// 1

补充:es6结构的对象不能为underfined 、null ,否则报错
const {a,b,c,d,e} = obj || {};

2.展开运算符

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.字符串拼接

模板字符串


const name = '小明';
const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;

4.使用includes判断  


 判断当前数组是否存在指定的条件,遍历下来存在返回true, 不存在则返回false
const condition = [1,2,3,4];

原本:if(type==1||type==2||type==3||type==4){

}
使用includes:
if( condition.includes(type) ){
   //...
}


5.使用find判断

find方法找到符合条件的项,不会继续遍历
const a = [1,2,3,4,5];
const result = a.find( 
  item =>{
    return item === 3
  }
)

6.obje.values和flat

一个部门JSON数据中,属性名是部门id,属性值是个部门成员id数组集合,现在要把有部门的成员id都提取到一个数组集合中。

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扁平化数组,将多维转化为一维数组
 const HHL = [1, 2, 3, [1, 2, 3, [4, 5]], 6]
 HHL.flat(Infinity) infinity
无限   不管多少层

7.ES6中的可选链操作符

ES5写法=>const name = obj && obj.name;

if(req && req.data && req.data.params && req.data.params.type === '200'){}

ES6写法=>const name = obj?.name;

if(req?.data?.params?.type === '200'){}

优化前: arr &&arr,length>0
优化后:arr?.length>0


8.非空判断

原本:if(value !== null && value !== undefined && value !== ''){
    //...
}
ES6:if((value??'') !== ''){
  //...
}

9.异步函数await使用


原本:

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)
      })
   })

}


改进:

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.有大量选中分支,需要过多if判断

优化前:

function chFruit(type='apple'){

if(type ==='apple'){
return '苹果'
}
else if(type ==='pear'){

return '梨'
}
else if(type ==='orange'){
return'橙子'
}



优化后:

function chFruit(type='apple'){
let fruit={

apple:'苹果',
pear:'梨',
orange:'橙'

}
retrun fruit[type]


}

11.找出总和、最小值和最大值

    使用reduce  或 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.打乱数组

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.将Object属性转成属性数组

使用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.排序

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.数组中过滤出值

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.防抖

防抖:
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.节流

节流:
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.随机排序数组

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.日期处理

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

有用详细:

你会用ES6,那倒是用啊! - 掘金

33个非常实用的JavaScript一行代码,建议收藏! - 掘金

56个JavaScript 实用工具函数助你提升开发效率! - 掘金

哈希空间-HashTang的个人空间

猜你喜欢

转载自blog.csdn.net/H_hl2021/article/details/125257077