Appearance
1、判断两个对象是否一致
js
isObjectValueEqual(a, b) {
var aProps = Object.getOwnPropertyNames(a)
var bProps = Object.getOwnPropertyNames(b)
if (aProps.length != bProps.length) {
return false
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i]
var propA = a[propName]
var propB = b[propName]
if (typeof propA === 'object') {
if (this.isObjectValueEqual(propA, propB)) { // 递归
return true
} else {
return false
}
}
else if (propA !== propB) {
return false
}
else {
}
}
return true
}
2、数组去重
js
let arr = [1, 2, 3, 3, 2, '1', 0, 1, 2]
let newArr = [...new Set(arr)]
// or
let newArr = Array.from(new Set(arr))
3、数组对象根据字段去重
js
export const uniqueArrayObject = (arr = [], key = 'id') => {
if (arr.length === 0) return
let list = []
const map = {}
arr.forEach((item) => {
if (!map[item[key]]) {
map[item[key]] = item
}
})
list = Object.values(map)
return list
}
4、根据某个属性排序
js
sortBy(attr, rev) { // 第二个参数没有传递 默认升序排列
if (rev === undefined) {
rev = 1
} else {
rev = (rev) ? 1 : -1
}
return function (a, b) {
a = a[attr]
b = b[attr]
if (a < b || (a === null && b !== null)) {
return rev * -1
}
if (a > b || (a !== null && b === null)) {
return rev * 1
}
return 0
}
}
5、判断路由是否相等
js
export const diff = (obj1, obj2) => {
delete obj1.close
var o1 = obj1 instanceof Object
var o2 = obj2 instanceof Object
if (!o1 || !o2) {
/* 判断不是对象 */
return obj1 === obj2
}
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false
// Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:
// 数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr)) => 0,1,2;
}
for (var attr in obj1) {
var t1 = obj1[attr] instanceof Object
var t2 = obj2[attr] instanceof Object
if (t1 && t2) {
return diff(obj1[attr], obj2[attr])
} else if (obj1[attr] !== obj2[attr]) {
return false
}
}
return true
}
6、判断值是否为空
JS
/**
* @params val:number string boolean [] {}
*/
export function validatenull(val) {
if (typeof val === 'string') {
if (val.trim() === '') return true
return false
}
if (typeof val === 'boolean') {
return false
}
if (typeof val === 'number') {
return false
}
if (val instanceof Array) { // []
if (val.length === 0) return true
} else if (val instanceof Object) { // [] {}
if (JSON.stringify(val) === '{}') return true
} else {
if (['null',null,'undefined',undefined].includes(val)) return true
return false
}
return false
}