数组
- map
进行投影,获取需要的属性
const data = [
{ name: '张三', sex: '男' },
{ name: '李四', sex: '男' }
],
// 获得所有的姓名
data.map(item => item.name)
- filter
过滤需要的数据,返回新数组
- find
查找是否存在某元素
const arr = [1, 2, 3]
arr.find((value, index, obj) => {
return value === 1
})
数字
函数 | 说明 | |
---|---|---|
parseInt() | 解析字符串返回整数 | |
Math.ceil(5/2) | 上取整 | |
Math.floor() | 上取整 | |
Math.round() | 四舍五入 | |
num.toFixed(2) | 保留 n 位小数 |
Promise
队列操作。可以在每个 Promise 里面 catch 或者,最终 catch
let promise = Promise.resolve()
this.selectionDeviceList.forEach((value, index, array) => {
promise = promise.then(() => {
return createPerson({
...this.params
}).then(response => {
// ... 处理逻辑
})
})
})
promise.finally(() => {
// finally 操作
})
工具函数
- 日期格式化
formatDate: function(date) {
let yyyy = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? '0' + MM : MM ;
let dd = date.getDate();
dd = dd < 10 ? '0' + dd : dd ;
let HH = date.getHours();
HH = HH < 10 ? '0' + HH : HH ;
let mm = date.getMinutes();
mm = mm < 10 ? '0' + mm : mm ;
let ss = date.getSeconds();
ss = ss < 10 ? '0' + ss : ss ;
let SSS = date.getMilliseconds();
if(SSS < 10) {
SSS = '00' + SSS;
} else if(SSS < 100) {
SSS = '0' + SSS;
}
return `${yyyy}/${MM}/${dd} ${HH}:${mm}:${ss}:${SSS}`;
}
- 下划线转小驼峰
function underScore2SmallCamel(originObj) {
if (!(originObj instanceof Object)) {
return originObj
}
if (originObj instanceof Array) {
return originObj.map(item => underScore2SmallCamel(item))
}
const newObj = {}
for (const originKey in originObj) {
if (Object.prototype.hasOwnProperty.call(originObj, originKey)) {
const newKey = originKey.replace(/_([a-z])/g, (p, ...m) => {
return m[0].toUpperCase()
})
newObj[newKey] = underScore2SmallCamel(originObj[originKey])
}
}
return newObj
}
- 小驼峰转大驼峰
function smallCamel2bigCamel(obj, newObj) {
if (obj instanceof Array) {
if (newObj === undefined) {
newObj = []
}
obj.forEach(function(value) {
smallCamel2bigCamel(value, newObj)
})
} else if (obj instanceof Object) {
if (newObj === undefined) {
newObj = {}
}
Object.keys(obj).forEach(function(key) {
const newKey = key.substr(0, 1).toUpperCase() + key.substr(1)
if (obj[key] instanceof Object) {
newObj[newKey] = {}
} else if (obj[key] instanceof Array) {
newObj[newKey] = []
} else {
newObj[newKey] = obj[key]
}
smallCamel2bigCamel(obj[key], newObj[newKey])
})
}
return newObj
}
- 大驼峰转小驼峰
export function bigCamel2SmallCamel(obj) {
if (obj instanceof Array) {
const newObj = []
obj.forEach(function(item, index) {
newObj[index] = bigCamel2SmallCamel(item)
})
return newObj
} else if (obj instanceof Object) {
const newObj = {}
Object.keys(obj).forEach(function(key) {
const result = /[a-z]/.exec(key)
let newKey = ''
if (result) {
const index = result.index
newKey = key.substring(0, index).toLowerCase() + key.substr(index)
} else {
newKey = key.toLowerCase()
}
newObj[newKey] = bigCamel2SmallCamel(obj[key])
})
return newObj
} else {
return obj
}
}