常用js工具函数[持续更新中...]

219 阅读3分钟

1,获取数组重复的元素

function getRepeats(arr){
    return arr.filter( function( item , idx ) {
        return arr.lastIndexOf( item ) != idx && idx == arr.indexOf( item )
    });
	// return [...new Set(arr.filter(function(item,idx,array){return array.indexOf(item) !== array.lastIndexOf(item)}))]-->
	// 也可用 array.indexOf(item,array.indexOf(item)+1) !== -1;
}

2,对象(数组)深拷贝

 function deepCopyObject(source){
        if (typeof source !== 'object') {
            return source;
        }
        const result = Array.isArray(source) ? [] : {};
        const sourceArr = Object.keys(source);
        for (const key of sourceArr) {
            result[key] = typeof source[key] === 'object' ? deepCopyObject(source[key]) : source[key];
        }
        return result;
    }

3,快速排序:也可直接活用数组自身的sort

function fastSort(arr) {
&emsp;&emsp;if (arr.length <= 1) { return arr; }
&emsp;&emsp;var midIndex = Math.floor(arr.length / 2) ;
&emsp;&emsp;var mid = arr.splice(midIndex, 1)[0];
&emsp;&emsp;var left = [],right = [];
&emsp;&emsp;for (var i = 0,len = arr.length; i < len; i++){
&emsp;&emsp;&emsp;&emsp;if (arr[i] < mid) {
&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;left.push(arr[i]);
&emsp;&emsp;&emsp;&emsp;} else {
&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;right.push(arr[i]);
&emsp;&emsp;&emsp;&emsp;}
&emsp;&emsp;}
&emsp;&emsp;return fastSort(left).concat([mid], fastSort(right));
};

4,判断NaN

function myIsNaN(v){return v !== v;}

5,Base64 转码

function b64Encode(str) {
  return btoa(encodeURIComponent(str));
}

function b64Decode(str) {
  return decodeURIComponent(atob(str));
}

b64Encode('你好') // "JUU0JUJEJUEwJUU1JUE1JUJE"
b64Decode('JUU0JUJEJUEwJUU1JUE1JUJE') // "你好"

6,颜色RGb转16进制

var rgb2hex = function(r, g, b) {
  return '#' + ((1 << 24) + (r << 16) + (g << 8) + b)
    .toString(16) // 先转成十六进制,然后返回字符串
    .substr(1);   // 去除字符串的最高位,返回后面六个字符串
}

7,判断数据类型(构造函数)

var type = function (o){
  var s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
['Null',
 'Undefined',
 'Object',
 'Array',
 'String',
 'Number',
 'Boolean',
 'Function',
 'RegExp'
].forEach(function (t) {
  type['is' + t] = function (o) {
    return type(o) === t.toLowerCase();
  };
});
type.isObject({}) // true

8,生成一个随机数等

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function random_str(length) {
  var ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  ALPHABET += 'abcdefghijklmnopqrstuvwxyz';
  ALPHABET += '0123456789-_';
  var str = '';
  for (var i=0; i < length; ++i) {
    var rand = Math.floor(Math.random() * ALPHABET.length);
    str += ALPHABET.substring(rand, rand + 1);
  }
  return str;
}

9,获得对象属性

//获得对象自身的可遍历属性
for ( var name in object ) {
  if ( object.hasOwnProperty(name) ) {
    
  }
}

//获得对象的所有可遍历属性(不管是自身的还是继承的)
for (p in o2) {
  console.info(p);
}

//获得对象的所有属性(不管是自身的还是继承的,也不管是否可枚举)
function inheritedPropertyNames(obj) {
  var props = {};
  while(obj) {
    Object.getOwnPropertyNames(obj).forEach(function(p) {
      props[p] = true;
    });
    obj = Object.getPrototypeOf(obj);
  }
  return Object.getOwnPropertyNames(props);
}

10,事件回调实现复制元素文本到粘贴板

const copyText = function(e){
		var copyText = e.target.innerText;
        var oInput = document.createElement('input');
        oInput.value = copyText;
		oInput.style.height = 0; 
		oInput.style.borderWidth = 0;
		oInput.style.margin = 0;
		oInput.style.padding = 0;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.parentNode.removeChild(oInput);
}

11,节流:滚动事件节流

var debounce = function(callback, delay, immediate){
    var timeout, result;
    return function(){
        var callNow;
        if(timeout)
            clearTimeout(timeout);
        callNow = !timeout && immediate;
        if(callNow) {
			console.log('immediate传入true的话会仅立即执行一次')
            result = callback.apply(this, Array.prototype.slice.call(arguments, 0));
            timeout = {};
        }
        else {
            timeout = setTimeout(()=>{
                callback.apply(this, Array.prototype.slice.call(arguments, 0));
            }, delay);
        }
    };
};
var s = debounce(()=>{
    console.log('yes...');
}, 2000,true);
window.onscroll = s;

12,如何给一串数字用千分制表示?比如9999999999变成9,999,999,999。

// 正则表达式的正向预查  ?=
const f = '99999999999'.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');
console.log(f);

13, 数字值正则表达式

const reg = /^(-?\d+)(\.\d+)?$/;

14, 解决js数字运算精度问题:toFixed(9)*1

(0.91+2.2).toFixed(9)*1
(3.11-2.2 + 0.000000001).toFixed(2)*1
(7.555).toFixed(2)   //7.55
(7.555 + 0.00000000001).toFixed(2) //7.56

15,时间字符串排序Date.parse()

rows.sort(function(a,b){
    return Date.parse(a.time) - Date.parse(b.time);//时间正序
});

16,正则:英文字母、中文、数字或三种情况组合组成

/^[\u4e00-\u9fa5a-zA-Z0-9]+$/.test(this.newAddName)

17, 导出excel的三种方式

1window.open():浏览器第一次会拦截窗口

2)get请求:location.href = excelGetUrl

3)post请求:
axios.post('/path/to/download/url', this.searchParams, {
  responseType: 'blob'
}).then(res => {
  let blob = res.data
  let reader = new FileReader()
  reader.readAsDataURL(blob)
  reader.onload = (e) => {
    let a = document.createElement('a')
    a.download = `表格名称.xlsx`
    a.href = e.target.result
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }
}).catch(err => {
  console.log(err.message)
})

18, 使整个页面内容可编辑,方便页面样式调试

document.body.contentEditable = true