const url ='http://example.com/index.html?a=1&b=2&c=3&d=true'const res =getQueryString(url)
console.log('res', res)// res {a: '1', b: '2', c: '3', d: 'true'}functiongetQueryString(url: any){const idx = url.indexOf('?')const urlParam = url.substr(idx +1, url.length)let urlObj ={}let urlObjItem = urlParam.length ? urlParam.split('&'):[]// 取得每一个参数项,let item =nulllet len = urlObjItem.length
for(let i =0; i < len; i++){
item = urlObjItem[i].split('=')var name =decodeURIComponent(item[0]),
value =decodeURIComponent(item[1])if(name){
urlObj[name]= value
}}return urlObj
}
js 之中常用的快速技巧方法
格式化input输入框
限制input只能输入正整整
<template>
value - {{ value }}<a-input placeholder="请输入" v-model.trim="value" @input="limitInpNum()" /></template>export default {
name: "About2",
components: {},
data(){return{
value: "",
};},
methods: {
// 限制input只能输入整数
limitInpNum(){
// console.log("this.value前", this.value); //this.value前 11e
let res = /^\d*$/.test(this.value);if(!res) this.value = this.value.replace(/[^\d]/g, "");
// console.log("this.value后", this.value); //this.value前 11},
},
};
日期相关
选中当前时间的上一天
// 获取前一天的日期
getTodayDate() {
let date2 = new Date(new Date(new Date().toLocaleDateString()).getTime());
let year = date2.getFullYear();
let momth = date2.getMonth() + 1;
momth = momth < 10 ? "0" + momth : momth;
let date = date2.getDate() - 1;
date = date < 10 ? "0" + date : date;
return year + "-" + momth + "-" + date;
},
1680254063618 毫秒 处理时间 17分钟 || 20小时 20天
// 处理时间 17分钟 || 20小时 20天dealTimeNum(timestamp){// console.log('timestamp', timestamp);let res ='';let date =newDate(Number(timestamp));let now =newDate();let diff = now.getTime()- date.getTime();// 获取两个日期对象之间的毫秒差let days = Math.floor(diff /(1000*60*60*24));// 将毫秒差转换为天数let hours = Math.floor(diff /(1000*60*60));// 将毫秒差转换为小时let minute = Math.floor(diff /(1000*60));// 将毫秒差转换为分钟let second = Math.floor(diff /(1000));// 将毫秒差转换为秒// console.log('days', days, 'hours', hours, 'minute', minute);if(days >0){
res = days +'天';}elseif(hours >0){
res = hours +'小时';}elseif(minute >0){
res = minute +'分钟';}elseif(second >0){
res = minute +'秒';}// console.log('res', res);return res;}
数组相关
数组的最大值 & 最小值
let arr =[100,888,2,5555,33,-111,7];let max = Math.max.apply(null,arr);let min = Math.min.apply(null,arr)
console.log('max',max,"min",min);// test.html:13 max 5555 min -111let Data=[{city:'w',收入:16.5},{city:'x',收入:14.5},{city:'e',收入:17.5},{city:'a',收入:1.5},{city:'y',收入:31.5},]let arr=[];for(let i=0;i<Data.length;i++){
arr.push(Data[i]['收入']);}var max=Math.max(...arr);
console.log(max)// 31.5
数组的去重
let res =[1,222,333,555,1,222,99,33]let res1 = res.reduce(function(pre, cur){return(pre.indexOf(cur)===-1)? pre.concat(cur): pre //满足pre这个数组的属性,有属于这个条件的时候,就返回到新数组内},[])
console.log('res1', res1);// [1, 222, 333, 555, 99, 33]
treeToArray(tree) {
var res = []
for (const item of tree) {
const { child, ...i } = item
if (child && child.length) {
res = res.concat(this.treeToArray(child))
}
res.push(i)
}
return res
}