preface
This paper mainly from date, array, object, AXIos,promise and character judgment these aspects of the work of some commonly used functions encapsulated, indeed can be directly referenced in the project, improve the efficiency of development.
Date of 1.
Date in the background management system is still used a lot, generally as a dimension of data storage and management, so it will involve a lot of date processing
1.1 New Date converts to YYYY-MM-DD HH: MM :ss
DatePicker Date picker gets the Date object by default, but we need to use yyyY-MM-DD in the background, so we need to convert it
Convert Fri Mar 23 2018 12:19:48 GMT+0800 to DD-MM-YYYY HH: MM: SS
export const dateToFormat=(date)=>{
date.toLocaleString("en-US", { hour12: false }).replace(/\b\d\b/g, '0$&').replace(new RegExp('/','gm'),'-')
}
Copy the code
Method 2: The value format attribute is provided from the 2.x version of element-UI, which allows you to directly set the value returned by the selector
1.2 Convert YYYY-MM-DD to new Date()
That is, to the date control to accept the type of direct initialization
export const forMatToDate=(date)=>
return new Date('2018-04-16 19:43:00');
}
Copy the code
1.3 Obtaining the current time YYYY-MM-DD HH: MM :ss
If you don’t reach 10, fill in 0
export default const obtainDate=()=>{ let date = new Date(); let year = date.getFullYear(); let month = date.getMonth() + 1; let day=date.getDate(); let hours=date.getHours(); let minu=date.getMinutes(); let second=date.getSeconds(); / / determine whether full 10 let arr = [month, day, hours, minu, second]; arr.forEach(item=>{ item< 10?" 0"+item:item; }) return year+'-'+arr[0]+'-'+arr[1]+' '+arr[2]+':'+arr[3]+':'+arr[4] }Copy the code
1.4 Convert the timestamp to YYYY-MM-DD HH: MM: SS
export default const returnTimestamp=(strTime)=>{
let middleDate=new Date(strTime)
return middleDate.toLocaleString('zh-CN',{hour12:false}).replace(/\b\d\b/g, '0$&').replace(new RegExp('/','gm'),'-')
})
Copy the code
1.5 Compare the YYYY-MM-DD time
If a single comparison is going to be complicated, we’ll just do a Number comparison
export default const compareTwo=(dateOne,dateTwo)=>{
return Number(dateOne.replace(/\-/g,""))<Number(dateTwo.replace(/\-/g,""))
}
Copy the code
1.6 Calculate the number of months between two dates in the format yyyY-MM-DD
export default const disparityFewMonth = (dateOne, dateTwo) => { let datesOne = dateOne.split('-').map(item => Number(item)); let datesTwo = dateTwo.split('-').map(item => Number(item)); const diff = [0, 0, 0].map((value, index) => { return datesOne[index] - datesTwo[index] }); Return (diff [0] * 12 + diff [1]) + 'month' + diff [2] + 'day}Copy the code
1.7 Acceptable parameters of the New Date object
1, new Date("month dd, YYYY hh:mm:ss"); 2, new Date("month dd, YYYY "); 3, new Date (yyyy, MTH, dd, hh, mm, ss); Note: This way, you must pass an integer; 4, new Date (yyyy, MTH, dd); 5, new Date (ms); 6. New Date(YYYY-MM-DD HH: MM: SS) GMT, January 1, 1970; Var mills = new Date().gettime (); Note: MTH: integer month, 0 (January) to 11 (December)Copy the code
An array of 2.
2.1 Check whether it is an array
export default const judgeArr=(arr)=>{ if(Array.isArray(arr)){ return true; }}Copy the code
2.2 Array de-set method
1. The common use of loops and indexOf(ES5 array method, can return the position of the first occurrence of the value in the array) is not detailed here, here is a set implementation using ES6.
2. A set is a new data structure, similar to an array, but with the feature that all elements are unique.
[add data structure set [3]
4. Set deduplication code
Export const changeReArr=(arr)=>{return array. from(new Set([1,2,2,3,5,4,5]))// convert [1,2,2,3,5,4,5] to Set data using Array Export const changeReArr=(arr)=>{return [...new set ([1,2,2,3,5,4,5])] The extension operator redefines an array by iterating over the values in a set... Is used for... Of traversal}Copy the code
Array.from can convert an array-like object with lenght attributes to an Array, and can also convert a traversable object such as a string to an Array. It takes 2 arguments, converts the object and the callback function,… And array. from are both ES6 methods
2.3 Pure array sort
So there’s a lot of bubbling and selection, so LET me write it here using sort
Export const orderArr=(arr)=>{arr.sort((a,b)=>{return a-b // return -(a-b)})}Copy the code
2.4 Sorting array objects
export const orderArr=(arr)=>{ arr.sort((a,b)=>{ let value1 = a[property]; let value2 = b[property]; return value1 - value2; // the sort method takes a function as an argument. Here we have a nested layer of functions that take object property names with //. The rest of the code is the same as normal})}Copy the code
2.5 The maximum value in the array
export const maxArr=(arr)=>{ return Math.max(... Export const maxArr=(arr)=>{return math.max. Apply (null,arr)}Copy the code
2.6 The “short-circuit” operations on every and some
Array short-circuiting is a name I coined myself, because there is a general requirement that one or all of the elements in an array should return true
Export const allTrueArr=(arrs)=>{return arr.every((arr)=>{return arr>20; Export Default const OneTrueArr=(arrs)=>{return if one of the items in the array satisfies export default const OneTrueArr=(arrs)=>{return arr.some((arr)=>{ return arr>20; Return true if one of the items in the array is satisfied, terminate the traversal, and return false if each item is not satisfied})}Copy the code
Above two scenarios and | | and & & short circuit operation is very similar, so I took a name is a short circuit calculation, the two cases, of course, can traverse to judge each item and then using break and return false to end loops and function.
2.7 Array filter and map processing methods
Filter: Filters the array values that meet a certain condition and returns a new array
export const filterArr = (arr, operator, judgeVal) => { return arr.filter(item => { if (operator == '>') { return item > judgeVal; } else if (operator == '<') { return item > judgeVal; } else if (operator == '==') { return item == judgeVal; }})}Copy the code
Map: Processing an array returns a new array
export const mapArr = (arr) => { return arr.map(item => item + 10;) If {} is omitted from the arrow function, it will return by default.Copy the code
3. The object
3.1 Object Traversal
Export const traverseObj=(obj)=>{for(let variable in obj){// for... If (obj.hasownProperty (variable)){console.log(variable,obj[variable])}}}Copy the code
3.2 Data Attributes of objects
1. Object attribute classification: data attribute and accessor attribute;
2. Data properties: a position containing data values, which can be read and written, and contains four features:
Enumerable: the writable property is returned via a for-in loop, exercising different control systems, which allows you to delete the property and modify the property via delete. The default is true, and the property can be modified as an accessor property. Indicates whether the value of an attribute can be modified. Value: Indicates the data value that contains the attribute. The default value is undefinedCopy the code
3. Modify the default properties of data attributes, using Object.defineProperty()
Export const modifyObjAttr=()=>{let person={name:' zhang3 ',age:30}; DefineProperty (person,'name',{writable:false, value:' li ', Enumerable :false})} Enumerable: disables any additional information, and controls no additional information.Copy the code
3.3 Accessor properties of objects
1. Four features of accessor properties:
Enumerable: The property can be returned via a for-in loop, and the default is false. The default is different, and the property can be deleted without any additional information. Function called when a property is read, default is undefined Set: Function called when a property is written, default is undefinedCopy the code
2. Definition: Accessor properties can only be defined by the object.defineProperty () method
Export const defineObjAccess=()=>{let personAccess={_name:' zhang3 ',//_ Object.defineProperty(personAccess,'name',{ get:function(){ return this._name; }, set:function(newName){ if(newName! ==this._name){ this._name=newName; this.editor++; }} // If only get method is defined, change object can only read})}Copy the code
The core of the reactive principle in VUE is to change data by hijacking the getters and setter properties of data via defineProperty
4.axios
4.1 Axios get method
export const getAjax= function (getUrl,getAjaxData) { return axios.get(getUrl, { params: { 'getAjaxDataObj1': Getajaxdata. obj1,//obj1 is an attribute of getAjaxData 'getAjaxDataObj2': GetAjaxData. Obj2}}). Then (data = > {/ / success returned}). The catch (err = > {/ / error returned})}Copy the code
4.2 Axios post method
export const postAjax= function (getUrl,postAjaxData) { return axios.post(postUrl, { 'postAjaxDataObj1': Postajaxdata. obj1,//obj1 is an attribute of postAjaxData 'postAjaxDataObj2': PostAjaxData. Obj2}). Then (data = > {/ / success returned}). The catch (err = > {/ / error returned})}Copy the code
4.3 Axios interceptor
There are two types of interceptors: request interceptor and response interceptor. Request interception is usually configured with the corresponding request header information (applicable to common request methods, although ajax GET method does not have a request header, but axios encapsulation), and the response is usually intercepted by Reponse. If the return result is [], it can be converted to 0
1. Request interception: Put the current city information into the request header
axios.interceptors.request.use(config => {
config.headers.cityCode = window.sessionStorage.cityCode //jsCookie.get('cityCode')
return config
},
Copy the code
2. Response interception: Process the results of rePONse
axios.interceptors.response.use((response) =>{ let data = response.data if(response.request.responseType === 'arraybuffer'&&! data.length){ reponse.date=0 } })Copy the code
5.promise
Promise is an easy-to-reuse asynchronous task management mechanism that encapsulates future values, addressing hell-callback and controlling the order of asynchrony
5.1 Application Method 1
export const promiseDemo=()=>{ new Promise((resolve,reject)=>{ resolve(()=>{ let a=1; return ++a; }). Then ((data) = > {the console. The log (data) / / the data value for + + a}). The catch (() = > {/ / error executing this})})}Copy the code
5.2 Application Method 2
Export const promiseDemo=()=>{promise.resolve ([1,2,3]). Then ((data)=>{// directly initialize a Promise and execute the resolve method Console. log(data)//data values are [1,2,3]})}Copy the code
6. Text box judgment
6.1 All numbers
Method 1 (easiest):
export const judgeNum1=(num1)=>{ if(typeof num1=='number'){ return true; }else{ return false; }}Copy the code
Method 2: isNaN
export const judgeNum1=(num1)=>{
if(!isNaN(num1)){
return true;
}else{
return false;
}
}
Copy the code
Note: when num1 is [] (an empty array), “” (an empty string), and null are converted to numeric type 0 during the procedure, so false is returned. Therefore, the above special cases can be typeof excluded.
Method three: re
export const judgeNum1=(num1)=>{ let reg=/^[0-9]*$/ if(! Reg.test (num1)){console.log('num1 is 0-9')}}Copy the code
6.2 The value can be numbers or letters only
This uses the re judgment to define a re :let reg=/^[0-9a-za-z]*$/g
6.3 The value can contain only digits, letters, and commas
Let reg=/^[0-9a-za-z,]*$/g
6.4 Check whether the number of digits to be entered is less than 16
Use the length attribute of the string directly
Export const judgeNum1=(num1)=>{if(num1.length>16){console.log('num1 exceeds 16 bits ')}}Copy the code
6.5 Remove Spaces between left and right Characters
Export const trimLeOrRi = (STR) = > {/ / delete Spaces at the ends of the return STR. Replace (/ (^ \ s *) | (\ s * $)/g, “”); }
The end of the
I’m glad you can still see it, because these are classes that you probably don’t need right now, but you can save for now. We can communicate with each other and use it directly for the next project development. Now the project is in a rush in March, which can really improve the development efficiency! Happy New Year to you all.