1.字符超出隐藏显示三个点
/**
* 自定义字符串长度
* @param str 待处理字符串
* @param defaultLen 默认限制长度
* @param limitTable 是否仅限制于表格处理,表格处理主要限制 表格中字段 长度
*/
static sliceStr (str: string, defaultLen = 19, limitTable = false) {
if (str) {
if (str.length > defaultLen) {
str = str.substr(0, defaultLen) + '...'
}
return str
}
if (!str && limitTable) return '/'
return str
}
2.深度对比两个对象是否相同
static compareDeep (origin: any, target: any) {
let p
if (typeof origin === 'number' && typeof target === 'number' && isNaN(origin) && isNaN(target)) {
return true
}
if (origin === target) {
return true
}
if (typeof origin === 'function' && typeof target === 'function') {
if ((origin instanceof RegExp && target instanceof RegExp) ||
(origin instanceof String || target instanceof String) ||
(origin instanceof Number || target instanceof Number)) {
return origin.toString() === target.toString()
} else {
return false
}
}
if (origin instanceof Date && target instanceof Date) {
return origin.getTime() === target.getTime()
}
if (!(origin instanceof Object && target instanceof Object)) {
return false
}
if (origin.prototype !== target.prototype) {
return false
}
if (origin.constructor !== target.constructor) {
return false
}
for (p in target) {
if (!origin.hasOwnProperty(p)) {
return false
}
}
for (p in origin) {
if (!target.hasOwnProperty(p)) {
return false
}
if (typeof target[p] !== typeof origin[p]) {
return false
}
if (!ComUtil.compareDeep(origin[p], target[p])) {
return false
}
}
return true
}
}
3.数值限制处理
export class FormatInputValue {
static intLen: number = 8
static decimalsLen: number = 2
/* 只允许输入整数 */
static parsetInt (v: string, intLen = FormatInputValue.intLen) {
return v.substr(0, intLen).replace(/[^\d]/g, '')
}
/* 只允许输入整数且支持可以保留负号 */
static parsetIntAndKeepMinus (v: string, intLen = FormatInputValue.intLen) {
v = v
.replace(/[^\d-]/g, '')
.replace(/-{1,}/g, '-')
.replace(/^-/, '$#$')
.replace(/-/g, '')
.replace('$#$', '-')
if (v.indexOf('-') > -1) intLen += 1
return v.substr(0, intLen)
}
/* 保留两位小数点,处理简单数字的转化,不处理表单数据格式化 */
static toFixedDecimal (v: string | number, decimalsLen = FormatInputValue.decimalsLen) {
if (!v) return '0.00'
return parseFloat(v + '').toFixed(decimalsLen)
}
/**
* 保留小数点,默认保留两位
* @param v 待处理字符串
* @param decimalsLen 小数点位数
* @param intLen 整数位数
*/
static toFixed (v: string, decimalsLen = FormatInputValue.decimalsLen, intLen = FormatInputValue.intLen) {
v = v
.substr(0, intLen + decimalsLen + 1)
.replace(/[^\d.]/g, '')
.replace(/^\./, '')
.replace(/\.{2,}/g, '.')
.replace('.', '$#$')
.replace(/\./g, '')
.replace('$#$', '.')
.replace(new RegExp(`^(\\d+)\\.(\\d{0,${decimalsLen}}).*$`), '$1.$2')
.replace(/^\d+/, (match: string) => {
return (parseFloat(match) + '').substr(0, intLen)
})
return v
}
/* 保留小数点和负号,小数点默认保留两位 */
static toFixedAndKeepMinus (v: string, decimalsLen = FormatInputValue.decimalsLen, intLen = FormatInputValue.intLen) {
v = v
.replace(/[^\d.-]/g, '')
.replace(/^\./, '')
.replace(/\.{2,}/g, '.')
.replace('.', '$#$')
.replace(/\./g, '')
.replace('$#$', '.')
.replace(/-{1,}/g, '-')
.replace(/^-/, '$#$')
.replace(/-/g, '')
.replace('$#$', '-')
.replace(new RegExp(`^(-?\\d+)\\.(\\d{0,${decimalsLen}}).*$`), '$1.$2')
if (v.indexOf('-') > -1) intLen += 1
v = v
.replace(/^-?\d+/, (match: string) => match.substr(0, intLen))
return v.substr(0, intLen + decimalsLen + 1)
}
/**
* 千分位数字
* @param v 数字
* @param decimalsLen 保留的小数点
*/
static formatMoney (v: string, decimalsLen = FormatInputValue.decimalsLen) {
if (!v) return v
v = parseFloat(v.replace(/[^\d.-]/g, '')).toFixed(decimalsLen)
const [int, decimal] = v.split('.')
const reverseInt = int.split('').reverse()
let t = ''
for (let i = 0, len = reverseInt.length; i < len; i++) {
t += reverseInt[i] + ((i + 1) % 3 === 0 && (i + 1) !== len ? ',' : '')
}
if (decimal) return t.split('').reverse().join('') + '.' + decimal
return t.split('').reverse().join('')
}
/**
* 转换限制
* @param reg 表达式
* @param val 转换值
* @param len 长度
*/
static conversionOf (reg:any, val:string, len?:number):string {
val = val.replace(reg, '')
if (len) {
val = val.length > len ? val.substr(0, len) : val
}
return val
}
/**
* 去除空格
*/
static removeEmpty = (val:any) => {
return val.replace(/(^\s*)|(\s*$)/g, '')
}
}
4.处理url
export default class HttpUtil {
/* 将 url 查询参数解析成为对象 */
static parseUrl (url: string) {
const query = url.split('?')[1]
if (query) {
const queryList = query.split('&')
const obj: any = {}
queryList.forEach(item => {
const [key, value] = item.split('=')
obj[key] = decodeURIComponent(value)
})
return obj
}
return {}
}
/* 浏览器中打开新的 tab */
static openTab (url: string) {
const c = url[0]
if (/\/|#/.test(c)) {
if (c === '/') url = url.replace('/', '#')
} else {
if (!/[a-zA-Z]/.test(c) || url.split('#').length > 1) {
message.error('请输入正确的页面地址')
return
}
}
const win = window.open('about:blank')!
win.location.href = `${process.env.WEB_URL}${url}`
}
}
5.判断浏览器内核
static getBrowserInfo (val:string):boolean {
let ua:any = navigator.userAgent.toLocaleLowerCase()
let browserType:string = ''
let browserVersion:string = ''
if (ua.match(/msie/) != null || ua.match(/trident/) != null) {
browserType = 'IE'
browserVersion = ua.match(/msie ([\d.]+)/) != null ? ua.match(/msie ([\d.]+)/)[1] : ua.match(/rv:([\d.]+)/)[1]
} else if (ua.match(/firefox/) != null) {
browserType = '火狐'
} else if (ua.match(/ubrowser/) != null) {
browserType = 'UC'
} else if (ua.match(/opera/) != null) {
browserType = '欧朋'
} else if (ua.match(/bidubrowser/) != null) {
browserType = '百度'
} else if (ua.match(/metasr/) != null) {
browserType = '搜狗'
} else if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
browserType = 'QQ'
} else if (ua.match(/maxthon/) != null) {
browserType = '遨游'
} else if (ua.match(/chrome/) != null) {
var is360 = SysUtil._mime('type', 'application/vnd.chromium.remoting-viewer')
browserType = is360 ? '360' : 'Chrome'
} else if (ua.match(/safari/) != null) {
browserType = 'Safari'
}
return val === browserType
}
6.利用 reduce 进行数据优化
数组去重
const data = [
{
name: '李...',
age: '24'
},
{
name: '王...',
age: '25'
},
{
name: '燕...',
age: '25'
},
{
name: '张...',
age: '25'
},
{
name: '孙...',
age: '25'
},
{
name: '钱...',
age: '25'
},
{
name: '宋...',
age: '25'
},
{
name: '燕...',
age: '24'
}
]
现在我们要去重里面name重复的对象,这时候我们可以利用reduce,例子如下:
const dataReducer = (prev, cur, idx) => {
let obj = {};
const { name } = cur;
obj[name] = cur;
return {
...prev,
...obj
}
}
const reducedData = data.reduce(dataReducer, {})
let newData = Object.values(reducedData)
7.获取 dom 元素节点的偏移量
如果有用过jQuery的童鞋,就一定不会忘记$('').offset()这个 api 的强大功能,这个 api 可以轻易获取元素的偏移量,那么如果我们不用jQuery该怎么实现呢?
我们先来看看例子:
var getOffset = function(el) {
var scrollTop =
el.getBoundingClientRect().top +
document.body.scrollTop +
document.documentElement.scrollTop
var scrollLeft =
el.getBoundingClientRect().left +
document.body.scrollLeft +
document.documentElement.scrollLeft
return {
top: scrollTop,
left: scrollLeft
}
}
首先我们先来看getBoundingClientRect()
这个方法。
getBoundingClientRect()
方法返回元素的大小及其相对于视口的位置。返回值是一个 DOMRect 对象,是与该元素相关的 CSS 边框集合 。
然后就是document.body.scrollTop
跟 document.documentElement.scrollTop
这两个是一个功能,只不过在不同的浏览器下会有一个始终为 0,所以做了以上的兼容性处理。所以当我们做拖拽功能的时候,就可以依赖上以上属性。
使用方法如下:
var el = document.querySelector('.moveBox')
getOffset(el) // {top: xxx, left: xxx}
8.过滤数组中相同的元素(最方便快捷方法之一)
const arr = [1, 2, 3, 4, 5, 6, 3, 4, 8];
const newArr = source_arr.filter(function (element, index, array) {
return array.indexOf(element) === index;
});
console.log(arr );
console.log(newArr );

9.过滤两个数组中相同的对象元素
let arr1=[{id:1,name:'张三'},{id:2,name:'李四'}]
let arr2=[{id:1,name:'张三'},{id:3,name:'王五'},{id:44,name:'王柳'},{id:45,name:'王琦'},]
let add=arr2.filter(item=>!arr1.some(ele=>ele.id===item.id))
console.log(add)

10.过滤数组中相同的对象元素
方法1
deteleObject = (obj) => {
var uniques = [];
var stringify = {};
for (var i = 0; i < obj.length; i++) {
var keys = Object.keys(obj[i]);
keys.sort(function(a, b) {
return (Number(a) - Number(b));
});
var str = '';
for (var j = 0; j < keys.length; j++) {
str += JSON.stringify(keys[j]);
str += JSON.stringify(obj[i][keys[j]]);
}
if (!stringify.hasOwnProperty(str)) {
uniques.push(obj[i]);
stringify[str] = true;
}
}
uniques = uniques;
return uniques;
}

亲测好用
方法2(使用Lodash)


网友评论