1,获取数组重复的元素
function getRepeats(arr){
return arr.filter( function( item , idx ) {
return arr.lastIndexOf( item ) != idx && idx == arr.indexOf( item )
});
}
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) {
  if (arr.length <= 1) { return arr; }
  var midIndex = Math.floor(arr.length / 2) ;
  var mid = arr.splice(midIndex, 1)[0];
  var left = [],right = [];
  for (var i = 0,len = arr.length; i < len; i++){
    if (arr[i] < mid) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }
  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('你好')
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({})
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.555 + 0.00000000001).toFixed(2)
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的三种方式
1)window.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