乐趣区

关于javascript:常用Js函数

1. 判断是不是数组

function isArray(arr){return typeof Array.isArray === 'function' ? Array.isArray(arr) : Object.prototype.toString.call(arr) === "[object Array]"
}

2. 判断是否对象

function isObject(obj) {return Object.prototype.toString.call(obj) === '[object Object]'
}

3. 判断是不是字符串

function isString(str){return Object.prototype.toString.call(str)=="[object String]"
}

4. 数组依据元素的某个 KEY 排序

// 数组排序
function arraysort(attr, rev) {if (rev == undefined) {rev = 1;}

    return function (a, b) {a = a[attr];
        b = b[attr];
        if (a < b) {return rev * -1;}
        if (a > b) {return rev * 1;}
        return 0;
    }
}

arr.sort(arraysort('totalInv',-1))

5. 格式化工夫

function dateFormater(formater, t){let date = t ? new Date(t) : new Date(),
        Y = date.getFullYear() + '',
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
    return formater.replace(/YYYY|yyyy/g,Y)
        .replace(/YY|yy/g,Y.substr(2,2))
        .replace(/MM/g,(M<10?'0':'') + M)
        .replace(/DD/g,(D<10?'0':'') + D)
        .replace(/HH|hh/g,(H<10?'0':'') + H)
        .replace(/mm/g,(m<10?'0':'') + m)
        .replace(/ss/g,(s<10?'0':'') + s)
}
退出移动版