js开发中经常用到的一些函数

我们码农在开发的过程中,是经常会用到一些比较普遍函数的。然而,一些大神则是可以手动迅速敲出来,亦或者引用公用方法来解决。我们这些自理尚浅的码农则是第一时间想到了度娘。。
泪流无数次,每次度娘出来的总会容易忘记!!

现在我给自己整理了一些项目中经常会用到的函数,对于我来说是非常实用的,不知道你们咧。。

1.求数组中最大值。

let arr = [{name:'data1',num:88},{name:'data2',num:66}];

function bigestNum(arr){

        let max = arr[0].num;
         for (let i = 0; i < arr.length - 1; i++) {
         max = max < arr[i+1].num ? arr[i+1].num : max
     }
       return max
 }
 
 

2.判断是否是图片格式
function isImage(str) {

   var reg = /\.(png|jpg|gif|jpeg|webp)$/;
   return reg.test(str);
}

3.数组去重
function listUniq(parmas){

            let list = parmas;
            let array = [];
            if(list.length == 0 || !list){
                return []
            }else{
                for(let i = 0;i

}

4.四舍五入保留2位小数,返回number类型

      function  numChange(num){
            if(num == 0 || !num){
                return 0
            }else{
                let num1 = parseFloat(num);
                let result = Math.round(num1*100)/100
                return result
            }
        }
        
        

5.处理日期格式,flag是createTime 则返回年月日 时分秒

fuction timeFormat(time, flag) {

            if (time == null || !time) {
                return '';
            }
            const date = new Date(time);
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const formatMonth = month < 10 ? `0${month}` : month;
            const formatDay = day < 10 ? `0${day}` : day;
        
            const hours = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours();
            const minutes = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes();
        
            if (flag == 'createTime') {
                return `${year}-${formatMonth}-${formatDay}  ${hours}:${minutes}`;
            } else {
                return `${year}-${formatMonth}-${formatDay}`;
            }
        }
        

额,就先提供这一些吧,第一次写博客,希望能得到大家的支持,也希望自己的IT之路能够越来越有趣。

你可能感兴趣的:(javascript前端)