web前端开发中常见的一些js方法封装

web前端开发中,我们经常用到一些常见的方法,有时候重复写的特别多,代码冗余、所以花时间整理了一些常见的js方法,判断是否为undefined、是否为NaN、js合并数组、js筛选数组对象、js替换数组对象中的key、js日期格式化等,备用!

//判断是否为undefined
function isUndefine(value) {
    return typeof(value) == undefined ? true : false
}
//判断对象是否为空
function isEmptyObj(obj) {
    return JSON.stringify(obj) == "{}" ? true : false
}
//判断是否NaN
function isNaNType(value) {
    if (typeof(value) === "number" && isNaN(value)) {
        return true;
    } else {
        return false;
    }
}
//合并两个数组
function ContactArr(arr1,arr2){
    return arr1.concat(arr2)
}
//帅选数组对象中符合条件的数组
//let arrObj =[{name:li,age:19},{name:zhao,age:22}]
function filtterArr(arrObj){
    let newarr= arrObj.filter((value, index, arr) => {
      return value.name == "li"//将数组对象中name==li的对象筛选出来变为新数组[{name:li,age:19}]
    })
}


// const array=[
//     {
//         name:'张三',
//         id:'111'
//     },
//     {
//         name:'李四',
//         id:'222'
//        }
// ]
function handleDealFilter(arr, key, replaceKey) {
     let newArr = [];
     arr.forEach((item, index) => {
       for (var i = 0; i < key.length; i++) {
         item[key] = item[replaceKey];
       }
       newArr.push(item);
     });
     return newArr;
   },
  // const newArr=handleDealFilter(array,'label','name');
   //得到的新数组 [
   //        {
   //            label:'张三',
   //            id:'111'
   //        },
       
   //        {
   //            label:'李四',
   //            id:'222'
   //        }
   //    ]
//日期格式化
function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        //
        "m+": (date.getMonth() + 1).toString(),     //
        "d+": date.getDate().toString(),            //
        "H+": date.getHours().toString(),           //
        "M+": date.getMinutes().toString(),         //
        "S+": date.getSeconds().toString()          //
        // 有其他格式化字符需求可以继续添加,必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
    //使用方式
    // let date = new Date()
    // dateFormat("YYYY-mm-dd HH:MM:SS", date)
    // >>> 2021-06-06 19:45:00`
}

 

posted @ 2021-01-04 16:59  li阿根  阅读(428)  评论(0编辑  收藏  举报