1、字符串补全长度
1、让一个字符串居中包裹在指定的可重复填充的字符串中间
centerPad('Hello', 13, 'abc') // => 'abcaHelloabca'
centerPad('Gook Luck!', 30, '*~') // => '*~*~*~*~*~Gook Luck!*~*~*~*~*~'
第一个参数为被包裹字符串,
第二个参数为最终的字符串长度,
第三个参数为用来填充的字符。
2、padStart()用于头部补全,padEnd()用于尾部补全。
第一个参数用来指定字符串的最小长度,第二个参数是用来补全的字符串
'xxx'.padStart(9, 'abc') // 'abcabxxx
const m = (dt.getMOnth()+1+'').padStart(2,"0")//月份不足2位补0
2、entries改造map为key,value数组格式
Object.entries() 可以把一个对象的键值以数组的形式遍历出来,结果和 for...in 一致,但不会遍历原型属性。
let obj = {"正常":1,"锁定":0};
let arrList = Object.entries(obj).map((i) => {
return {
key: i[1],
value: i[0]
}
})
console.log(JSON.stringify(arrList))
// [{"key":1,"value":"正常"},{"key":0,"value":"锁定"}]
3、根据后端返回的一个字段排序数组
let res= [{"id": 16,'code':'8.4'},
{"id": 12,'code':'5.4'},
{"id": 14,'code':'1.4'},
{"id": 15,'code':'3.4'},
{"id": 10,'code':''}]
//自定义规则排序
var ids = [15,12,10]
// 你建一个新的数组变量,然后遍历ids数组,匹配ids[i].id与之相对应的数据
var newArr = []
for(var i=0;i<ids.length;i++){
for(var j=0;j<res.length;j++){
if(ids[i]==res[j].id){
newArr.push(res[j])
}
}
}
//排序方法1
console.log(res.data.sort((a,b) => {return b.code - a.code}))
排序方法2
res.sort((a, b) => {
return (a.code + '') > (b.code + '')? 1 : -1;
})
4、从对象创建键-值对数组
const keyValueToArray = object => Object.keys(object).map(el => [el, object[el]])
// Example
keyValueToArray({id: 4, age: 2})
// [['id', 4], ['age', 2]]
console.log(keyValueToArray({x:1, y:2, z:3}));
// [['x', 1], ['y', 2], ['z', 3]]
5、字符串长度超出的部分补...
str?(str.length>12?(str.substring(0,12))+"...":str):"")
// 过滤器写法
filters: {
formatStrLen(val) {
if (!val) return '';
if (val.length > 10) {
return val.slice(0,10) + '...'
}
return val
},
},
6、根据 key值查找数组对象中所有符合的对象
let arr = [{ "code": "001", "name": "合成树脂" }, { "code": "002", "name": "合成橡胶" }, { "code": "003", "name": "有机化工品" }]
//arr 原数组 key匹配值001
function getObjByKey(arr, key) {
let obj = {}
obj = arr.find(item => {
return item.code === key // 筛选出匹配数据
})
return obj
}
console.log('', getObjByKey(arr, '001'));
// {code: "001", name: "合成树脂"}
7、数组对象的某一个key匹配固定的对象的key,显示页面value
let hotelArr = [{ "lowestPrice": null, "hotelIdPlt": "40101876", "channel": "ELONG", "geoCode": "0101", "id": 1633398, "status": true }, { "lowestPrice": null, "channel": "MEIYA", "geoCode": "c10750", "id": 1967347, "status": true }, { "lowestPrice": null, "channel": "MEIYA", "geoCode": "c10750", "id": 1973816, "status": true }, { "lowestPrice": null, "channel": "MEIYA", "geoCode": "c10750", "id": 2005216, "status": true }, { "lowestPrice": null, "channel": "MEIYA", "geoCode": "c10750", "id": 2018202, "status": true }, { "lowestPrice": null, "channel": "MEIYA", "geoCode": "c10750", "id": 2041820, "status": true }, { "lowestPrice": null, "channel": "TRIPNO1", "geoCode": "001001001", "id": 2320286, "status": true }]
// 数组对象的某一个key匹配固定的对象,显示页面value
// 比如chanel是ELONG,MEIYA,显示艺龙,美亚
function getGroup(arr) {
let obj = {
'ELONG': '艺龙', 'JINJIANG': '锦江', 'CYTS': '中青', 'QUNAR': '去哪儿', 'BOTAO': '铂涛',
'UPER8': '速8', 'VIENNA': '维也纳', 'MEIYA': '美亚', 'TRIPNO1': '国旅'
}, objHash = {}
arr.forEach(item => {
if (!objHash[item.channel]) {
objHash[item.channel] = obj[item.channel]
}
})
return Object.values(objHash).join(',')
}
console.log(getGroup(hotelArr))
//艺龙,美亚,差旅
8、日历插件默认今天和结束日期+1年
startDate: new Date(),
endDate: new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 364),
// 2020-09-04 - 2021-09-03
9、根据一组key找到对应的value
//应用场景,下拉选择多个城市的时候,绑定了id,同时要传城市名
//cityCode:'01,02,04' cityName='北京,上海,重庆'
let arr = [
{ code: '01', name: '北京' },
{ code: '02', name: '上海' },
{ code: '03', name: '长城' },
{ code: '04', name: '重庆' },
]
let keys = ["01", "02", "04"]
let res = []
arr.forEach(item => {
let index = keys.indexOf(item.code)//注意keys和item.code类型一致
if (index > -1) {
res[index] = item.name
}
})
// 补充:有时候会遇到res里面有空值,加filter
var r = res.filter(s=>s && s.trim())
console.log(r);
console.log(r.join(','));
// 牡丹卡,金穗卡,龙卡
10、将数组中指定元素移到第一位
// vue将数组中指定元素移到第一位,场景比如城市是郑州,排序第一位
let res = {
baseFast: '无早',
list: [
{ "id": 01, "code": "002", "name": "meiya" },
{ "id": 02, "code": "003", "name": "qunaer" },
{ "id": 03, "code": "004", "name": "zhengzhou" },
{ "id": 04, "code": "005", "name": "qitian" },
]
}
let arr = res.list; //数组;
let key = '004' //指定key
let index = arr.findIndex(item => item.code == key); //根据 已知id(this.a_id) 获取在数组中的位置(index);
let delIt = arr.splice(index, 1); //从数据组移出当前数据;
arr.splice(0, 0, ...delIt); // 把当前数据插入到数组第一位;
console.log(JSON.stringify(res));
// {"baseFast":"无早","list":[{"id":3,"code":"004","name":"xiecheng"},{"id":1,"code":"002","name":"meiya"},{"id":2,"code":"003","name":"zhengzhou"},{"id":4,"code":"005","name":"qitian"}]}
11、改造数组对象的value值
//将结果集改造成这样[{itemcode:'1'itemname:'AD/安道尔'}]
let res = {"message":"成功","status":true,"data":{"bean":{"countryList":[{"countrycode":"AD","namecn":"安道尔","countryid":1},{"countrycode":"AE","namecn":"阿联酋","countryid":228}]}}}
let arrList = [{
itemcode: '0',
itemname: '请选择'
}]
let arr = res.bean.countryList
if (arr) {
let dataList = arr.map(item => {
let row = Object.values(item) || []
return {
itemcode: row[2],
itemname: row[0] + '/' + row[1]
}
})
arrList.push(...dataList)
}
console.log(JSON.stringify(arrList));
//[{"itemcode":"0","itemname":"请选择"},{"itemcode":1,"itemname":"AD/安道尔"},{"itemcode":228,"itemname":"AE/阿联酋"}]
12、将数组对象里面的小数组里面的某一个小数组合并成大数组
let arr = [
{ itemcode: '00', priceArr: [{ date: '2020-11-01', price: '14' }, { date: '2020-11-02', price: '15' }] },
{ itemcode: '01', priceArr: [{ date: '2020-11-03', price: '24' }, { date: '2020-11-14', price: '16' }] },
{ itemcode: '02', priceArr: [{ date: '2020-11-05', price: '19' }, { date: '2020-11-26', price: '17' }] }]
var arr1 = []
arr.map((item) => {
// arr1.push(...item.price); // 方法1
arr1 = arr1.concat(item.priceArr); // 方法2
})
document.write(JSON.stringify(arr1));
// [{"date":"2020-11-01","price":"14"},{"date":"2020-11-02","price":"15"},{"date":"2020-11-03","price":"24"},{"date":"2020-11-14","price":"16"},{"date":"2020-11-05","price":"19"},{"date":"2020-11-26","price":"17"}]
13、关于日期处理
const thetime = new Date(new Date().setHours(0, 0, 0, 0) + 15 * 60 * 60 * 1000 - 1) // 获取当天14:59:59的时间
var curDate = new Date() //现在时间
if (curDate <= thetime) {//小于15点日审或者夜审}
14、Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组
const obj = { 0: 'a', 1: 'b', 2: 'c' };
let arr = Object.entries(obj).map(i => {
return {
itemcode: i[0],
itemname: i[1]
}
})
console.log('res--', JSON.stringify(arr));
//[{"itemcode":"0","itemname":"a"},{"itemcode":"1","itemname":"b"},{"itemcode":"2","itemname":"c"}]
15、格式化接口返回的值显示页面
// 接口返回1个格式化
function getGroup(str) {
let obj = {
'0': '无星级',
'1': '一星级',
'2': '二星级',
'3': '三星级',
'4': '四星级',
'5': '五星级'
}
return obj[str]
}
//接口返回"1,3" ,页面显示周一,周三适合多个格式化
function getWeek(str) {
let dayHash = {
1: '周一',
2: '周二',
3: '周三',
4: '周四',
5: '周五',
6: '周六',
7: '周日'
}
str = str.split(',')
if (str.length === 7) {
return '全部'
}
return str.map(item => {
return dayHash[item]
}).join('、')
}
console.log('log1--', getGroup('1')); //log1-- 一星级
console.log('log2--', getWeek('1,3'));// log2-- 周一、周三
16、table格式化code数据
<script type="text/javascript">
let res = {
"errorMessage": null,
"message": "成功",
"status": true,
"data": {
"bean": {
"2Z": {
"id": 326,
"flightCode": "2Z",
"simpnamecn": "长安航空",
},
"LT": {
"id": 195,
"flightCode": "LT",
"simpnamecn": "龙江航空",
},
"A6": {
"id": 181,
"flightCode": "A6",
"simpnamecn": "云南红土航空股份",
}
}
}
}
let resData = res.data.bean || {}
function policyMapFormate(codeStr) {
if (!codeStr) return []
return codeStr.split('/').map(item => {
let {
flightCode = '',
simpnamecn = ''
} = resData[item] || {}
if (flightCode && simpnamecn) {
return `${flightCode}-${simpnamecn}`
}
return ''
})
}
let items = [{ id: 80, flightCode: "2Z/A6" }, { id: 81, flightCode: "2Z/LT/A6" }]
// 两个接口,列表接口返回{flightCode="2Z/A6"},根据数据字典接口 ("A6":{"flightCode": "A6","simpnamecn": "云南红土航空股份",})
// 要求:比如返回2Z/A6页面展示["2Z-长安航空", "A6-云南红土航空股份"]
//1、分割2Z/A6 split
//2、提取里面的code和name进行拼接并返回code-name这样的格式
//3、复制给tabledata里面的值
//4、页面插槽用slot,可以进行换行
let tabData = (items || []).map(
(item, index) => {
// item.orderno = index + 1
item.policyMapData = policyMapFormate(item.flightCode) // 获取航空公司描述信息
item.policiesSlideDown = false // 协议政策下拉状态
return item
})
console.log(tabData);
// <template v-slot:policyMap="{ row }">
// <div class="row-item"
// v-for="(item, index) in row.policyMapData"
// :key="index">
// {{ item }}
// </div>
// </template>
// ["2Z-长安航空", "A6-云南红土航空股份"]
</script>
<!-- 协议政策 -->
<template v-slot:policies="{ value, row }">
<div v-if="value.length">
<div class="row-item"
v-for="(item, index) in (row.policiesSlideDown ? value : value.slice(0,1))"
:key="index">
{{ item.policyName }}/航线{{ item.applyAirline }}舱/前返{{ item.discount }}/有效期{{ item.saleDateEnd }}
</div>
<div class="row-item"
v-if="value.length >= 2">
<el-link type="primary"
@click="row.policiesSlideDown = !row.policiesSlideDown">
<template v-if="row.policiesSlideDown">
收起<i class="iconfont icon-uparrow"></i>
</template>
<template v-else>
更多<i class="iconfont icon-downarrow"></i>
</template>
</el-link>
</div>
</div>
<span v-else>无协议政策</span>
</template>
// 数据结构是这样的:
"policies":[
{
"exceptAirline":"SXZ-PEK/SXZ-CTU,",
"createTime":"2020-07-21 10:19:28",
"saleDateEnd":"2020-09-05",
"updateTime":"2020-07-31 19:20:07",
"status":1,
"customCodeId":87,
"travelDates":[
],
"opAid":"6428960363294326165",
"discount":10,
"flightRuleId":3003,
"id":180,
"exceptFlight":"SXZ-PEK/SXZ-CTU,",
"policyName":"erwerwere",
"saleDateStart":"2020-05-05",
"applyAirline":"SXZ-PEK/SXZ-CTU,",
"opName":"赵瑾强",
"classCode":"SXZ-PEK/SXZ-CTU,",
"policyNo":"SFZC200721101927075847",
"applyFlight":"SXZ-PEK/SXZ-CTU,",
"ticketSupplier":"221,143,13900054",
"applyComs":[
]
},
{
"exceptAirline":"SXZ-PEK/SXZ-CTU,",
"createTime":"2020-07-21 10:17:38",
"saleDateEnd":"2020-09-05",
"updateTime":"2020-07-31 19:19:08",
"status":1,
"customCodeId":87,
"travelDates":[
],
"opAid":"6428960363294326165",
"discount":10,
"flightRuleId":3002,
"id":179,
"exceptFlight":"SXZ-PEK/SXZ-CTU,",
"policyName":"erwerwere",
"saleDateStart":"2020-05-05",
"applyAirline":"SXZ-PEK/SXZ-CTU,",
"opName":"赵瑾强",
"classCode":"SXZ-PEK/SXZ-CTU,",
"policyNo":"SFZC200721101737668785",
"applyFlight":"SXZ-PEK/SXZ-CTU,",
"ticketSupplier":"001,20190235,143,20190228,221",
"applyComs":[
]
}
]
17、判断非空
//把数字0看做非空,可以过滤空字符串,空对象,undefined,以及null
function isEmpty(targe){ if(typeof targe ==undefined) return true; if(typeof targe =='number') return false; if(typeof targe =='string'){ if(targe==''){ return true; }else{ return false; } } if(targe ===null){ return true; } if(typeof targe == 'object'){ for(var i in targe){ return false; } return true; } return false; }
18、实现字符串长度截取
//str字符创 len目标长度
function cutstr(str, len) {
var temp;
var icount = 0;
var patrn = /[^\x00-\xff]/;
var strre = "";
for (var i = 0; i < str.length; i++) {
if (icount < len - 1) {
temp = str.substr(i, 1);
if (patrn.exec(temp) == null) {
icount = icount + 1;
} else {
icount = icount + 2;
}
strre += temp;
} else {
break;
}
}
return strre + "..."
}
11、ceshi