js方法

124 阅读1分钟
  • 判断是否是复杂类型

typeof 可以正确识别:Undefined、Boolean、Number、String、Symbol、Function 等类型的数据,但是对于其他的都会认为是 object,比如 Null、Date 等,所以通过 typeof 来判断数据类型会不准确。但是可以使用 Object.prototype.toString 实现。

function typeOf(obj) { 
let res = Object.prototype.toString.call(obj).split(' ')[1]    
res = res.substring(0, res.length - 1).toLowerCase()    
return res}
typeOf([])    // 'array'
typeOf({})    // 'object'
typeOf(new Date)  // 'date'
typeof(2// number

  • 数字转为千分位计数法

    thousands_format_yuan (num) {
    if (num == 0) { return '0'; } else if (num == '-' || num == 'null') { return '-' } else if (_.isNaN(num)) { return '0'; } else {
    const reg = /%+/;
    if (reg.test(num)) {
    return (num && num.toString().replace(/(^|\s)\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+)/g, ','))); } else if (num < 0) { const n = Math.abs(Number(num)); const b = (n && n.toString().replace(/(^|\s)\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+)/g, ','))); const c = '-' + b; return c; } else { return (num && num.toString().replace(/(^|\s)\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))); } } }

  • 动态获取表格高度

    created () {   
        const that = this;        
        window.addEventListener('resize', that.getHeight());   },
    
    态计算表格高度方法    
    getHeight () {       
         this.tableHeight = document.documentElement.clientHeight - (60 + 60 + 50) + 'px'; // 获取浏览器高度减去顶部导航栏    
    },
    
    watch: {        
       tableHeight (newVal, oldVal) {            
           window.addEventListener('resize', this.getHeight());        
       }
    },
    
    destroyed () {        
       const that = this;        
        window.removeEventListener('resize', that.getHeight());    
    }