You don’t have to read it, just collect it, and you’ll need it later.
Today’s digital problems are often encountered in front-end development, and the solution is a little too rough, and will be updated in the future.
This article is on my Github to learn and improve together. Editor is not talented, if there is a problem, welcome elegant, if there is a harvest, please feel free to humiliate me with star. Github address attached
Take advantage of JavaScript’s native methods to solve problems
Although front-end page and data processing look simple, but a good front-end engineer for the details of the control is also very important, how to properly deal with the business also reflects the front-end engineer’s performance optimization skills
Gets the maximum and minimum array values
- Use the sort sorting method
- If you sort an array, the first and last of the array are the maximum and minimum
Let arr =,2,3,4,5,6,7 [1]; arr.sort(function (a, b) { return a-b; }); Let min = arr[0]; // let min = arr[0]; // 1 let max = arr[arr.length - 1]; / / 7Copy the code
- Use the Max /min method in Math
- You can do this using Apply. So apply is passing in an array
Let arr =,2,3,4,5,6,7 [1]; let max = Math.max.apply(null, arr); let min = Math.min.apply(null, arr); The console. The log (Max, min) / / 7, 1Copy the code
Rounding floating-point numbers
- Discard the fractional part and keep the integer part
parseInt(7/2)
- If you round up, if you have a decimal, you add 1 to the whole number
Math.ceil(7/2)
- rounded
Math.round(7/2)
- Take down the whole
Math.floor(7/2)
- Note: Both are JS built-in objects
Array to heavy
- ES6
,1,1,2,2,2,3,4 arr2 = [1] arr1 = Array. The from (new Set (arr2)) / / arr1 = [1, 2, 3, 4]Copy the code
- Push () to heavy
let arr3 = []; for(var i = 0; i < arr.length; I++) {(function (I) {if (arr3. IndexOf (arr) [I] = = 1) {/ / does not contain the value it returns - 1 arr3. Push (arr [I]); } }(i)) } console.log(arr3); // If the first occurrence of the i-th item in the current array is not at the I position in the current array, then the i-th item is repeated and is ignored. Let arr4 = [arr[0]]; for(var i = 1; i < arr.length; i++) { (function(i) { if(arr.indexOf(arr[i]) == i) { arr4.push(arr[i]); } }(i)) } console.log(arr4);Copy the code
- Sort ()
let arrSort = arr.sort(); let arr5 = []; for(let i = 0; i< arrSort.length; i++) { if(arrSort[i] ! = arrSort[i+1]) { arr5.push(arrSort[i]); } } console.log(arr5);Copy the code
- The splice () to heavy
for(let i = 0, len = arr6.length; i < len; i++) {
for(let j = i + 1; j < len; j++) {
if(arr6[i] === arr6[j]) {
arr6.splice(i,1);
len--;
j--;
}
}
}
console.log(arr6);
Copy the code
Use filter, map, every, find, and other higher-order traversal functions added to ES6
- Remove false from the array
const array = [3, 4, 5, 2, 3, undefined, null, 0, ""];
const compact = arr => arr.filter(Boolean);
compact(array);
//[3, 4, 5, 2, 3]
Copy the code
- Determine if all users are adults
const users = [
{ name: "Jim", age: 23 },
{ name: "Lily", age: 17 },
{ name: "Will", age: 35 }
];
users.every(user => user.age >= 18);
//false
Copy the code
- Determine if any of the users are over 30
const users = [
{ name: "Jim", age: 23 },
{ name: "Lily", age: 17 },
{ name: "Will", age: 35 }
];
users.find(item => item.age>30);
//{name: "Will", age: 35}
Copy the code
JS determines the click area
- Application scenario: When a popover is displayed, the popover is automatically closed by clicking elsewhere on the page.
<div id="facePanel"> <div v-show="showFace"> </div> </div> // JavaScript handleClick(e) { let facePanel = document.getElementById('facePanel') if(! facePanel.contains(e.target) && this.$refs.editContent.showFace){ this.$refs.editContent.showFace = false } }Copy the code
Use regular expressions to solve problems
<input>
Label input restriction
- You can only enter numeric code in the text box (not even the decimal point)
<input onkeyup="this.value=this.value.replace(/\D/g,'')"
onafterpaste="this.value=this.value.replace(/\D/g,'')">
Copy the code
- Only numbers can be entered. Decimal points can be entered.
<input onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')"> <input Name =txt1 onchange=" if(/\D/.test(this.value)){alert(' enter numbers only '); this.value=''; } ">Copy the code
- Number and decimal point method two
<input type=text tvalue="" ovalue="" onkeypress=" if(! this.value.match(/^[\+\-]? \d*? \.? \d*? $/))this.value=this.t_value; else this.tvalue=this.value; if(this.value.match(/^(? : [\ + \]? \d+(? :\.\d+)?) ? $/))this.ovalue=this.value" onkeyup="if(! this.value.match(/^[\+\-]? \d*? \.? \d*? $/))this.value=this.t_value; else this.tvalue=this.value; if(this.value.match(/^(? : [\ + \]? \d+(? :\.\d+)?) ? $/))this.ovalue=this.value" onblur="if(! this.value.match(/^(? : [\ + \]? \d+(? :\.\d+)? |\.\d*?) ? $/))this.value=this.o_value; else{if(this.value.match(/^\.\d+$/))this.value=0+this.value; if(this.value.match(/^\.$/))this.value=0; this.ovalue=this.value}">Copy the code
- Only letters and Chinese characters can be entered
<input onkeyup="value=value.replace(/[\d]/g,'') "
onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[\d]/g,''))"
maxlength=10 name="Numbers">
<input onkeyup="value=value.replace(/[^\a-zA-Z\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\a-zA-Z\u4E00-\u9FA5]/g,''))"
maxlength=10 name="Numbers">
Copy the code
- You can enter only letters and digits, not Chinese characters
<input onkeyup="value=value.replace(/[^\w\.\/]/ig,'')">
Copy the code
- Only numbers and English can be entered
<font color="Red">chun</font>
<input onKeyUp="value=value.replace(/[^\d|chun]/g,'')">
Copy the code
- A maximum of two digits can be entered after the decimal point. No letters or symbols can be entered:
<input onKeyPress=" if((event.keyCode<48 || event.keyCode>57) && event.keyCode! =46 || /\.\d\d$/.test(value)) event.returnValue=false">Copy the code
- A maximum of two digits (digits, letters, Chinese) can be entered after the decimal point. You can enter operation symbols:
<input onkeyup="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')">
Copy the code
- If the type of input is set to number, you can enter e
<input type='number' onkeypress='return( /[\d]/.test(String.fromCharCode(event.keyCode) ) )' />
Copy the code
/ / match email let reg = / ^ (| [a zA - Z] [0-9]) | \ (\ w) + @ [a - zA - Z0-9] + \. ([a zA - Z] {2, 4}) $/ / phone number (new) matching the let reg = / ^ 1 [0-9] {10} $/; / / phone number (old) matching the let reg = / ^ 1 [3 4 5 7 | | | | 8] [0-9] {9} $/; Let reg = /^(? ! ([0-9] + $)? ! [a zA - Z] + $) [0-9 a zA - Z] 16th {8} $/; / / match domestic phone number 0510-4305211 let reg = / \ d {3} - \ d {8} | \ d {4} - \ d {7} /; / / match id number let reg = / (^ \ d {15} $) | | (^ \ d {and} $) (^ \ d {and} (\ d | | X) X $) /; Let reg = /[1-9][0-9]{4,}/; let reg = /[1-9][0-9]{4,}/; Reg = /\d+\.\d+\.\d+\.\d+ \.\d+\.\d+/; Let reg = /^[\u4e00-\u9fa5]*$/; let reg = /^[\u4e00-\u9fa5]*$/;Copy the code
JS determines whether the string is entirely blank
let test = " \n ";
if(test.match(/^\s+$/)){
console.log("all space or \\n")
}
if(test.match(/^[ ]+$/)){
console.log("all space")
}
if(test.match(/^[ ]*$/)){
console.log("all space or empty")
}
if(test.match(/^\s*$/)){
console.log("all space or \\n or empty")
}
Copy the code
Common regular matching
/^\\d+$/
// Non-negative integer (positive integer + 0)/ ^ [0-9] * [1-9] [0-9] * $/
/ / positive integer/^((-\\d+)|(0+))$/
// Non-positive integer (negative integer + 0)/ ^ - [0-9] * [1-9] [0-9] * $/
/ / negative integer/ ^ -? \\d+$/
/ / integerlet reg = /^([^0][0-9]+|0)$/; if (reg.test(params.xzd2BorrowRate)) { params.xzd2BorrowRate += '.0'; }
/ / integer/^\\d+(\\.\\d+)? $/
// Non-negative floating point number (positive floating point number + 0)/ ^ (([0-9] + \ \ [0-9] * [1-9] [0-9] *) | ([0-9] * [1-9] [0-9] * \ \ [0-9] +) | ([0-9] * [1-9] [0-9] *)) $/
// A positive floating point number/^((-\\d+(\\.\\d+)?) | (0 + (\ \. 0 +)?) ) $/
// Non-positive floating-point (negative floating-point + 0)/ ^ (- (([0-9] + \ \ [0-9] * [1-9] [0-9] *) | ([0-9] * [1-9] [0-9] * \ \ [0-9] +) | ([0-9] * [1-9] [0-9] *))) $/
// Negative floating-point number/ ^ (-? \\d+)(\\.\\d+)? $/
/ / floating point numberreplace(/[^0-9]/ig, "")
// Keep only numbers
JS expands the checkbox click area
- Trial scenario: Click td in the table to select the event, or click on the parent node to trigger the event
- What to do: Add a click event to the TD element and trigger the checkbox click event inside the click event:
<td onclick="clickTd($(this))">
<input type="checkbox" name="task" onclick="oncheckAll(event)">
</td>
function clickTd($t){
$t.children("input").click();
}
Copy the code
-
Bug emerged. When you click on the Checkbox, because the page elements overlap, the click event is passed up, and first the click event of checkbox is triggered, then the click event of TD is triggered, and then the click event of TD is triggered again, so the checkbox is clicked twice. So you need to stop the checkbox click event when it’s finished executing.
-
Solution: Add interception to checkbox click event:
function oncheckAll(event){
event.stopPropagation();
}
Copy the code
Calculate the timestamp interval
let date1=new Date(); Let date2=new Date(); / / end time let date3 = date2. GetTime () - date1. GetTime () / / the number of milliseconds between the -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Var leave1=date3%(24*3600*1000) var leave1=date3%(24*3600*1000 Hours = math.floor (leave1/(3600*1000)) var leave2=leave1%(3600*1000) // Number of milliseconds left after calculating hours var Leave3 =leave2%(60*1000) var leave3=leave2%(60*1000) var leave3=leave2%(60*1000) var Leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000 = leave3.1000Copy the code
JS extracts consecutive numbers from a string
let str = "013d1we22ewfa33rr4rwq0dsf00dsf9fas999"; Let getNum = function (Str, isFilter) {/ / used to determine whether to remove the continuous 0 isFilter = isFilter | | false; if (typeof Str === "string") { // var arr = Str.match(/(0\d{2,})|([1-9]\d+)/g); / / / "[1-9] \ d {1} / g", means to match 1 to 9, more than one digit number (not including single digit). / / / \ d {2} / "g", say at least two Numbers match up to an infinite digits var arr = Str. Match (isFilter? /[1-9]\d{1,}/g : /\d{2,}/g); console.log(arr); Return arr.map(function (item) {return arr.map(function (item) {return arr.map(function (item) {return arr.map(function (item) {return arr.map(function (item) {return arr.map(function (item) {return arr.map(function (item) {return arr.map(function (item) {return arr. // Return parseInt(item); Return item = return item; return item = return item; }); } else { return []; } } console.log(getNum(str)); // The default is not to add 1, that is, the extracted 0 will not be removedCopy the code
JS gets the project root directory
Function getRootPath(){// get the current url, for example: http://localhost:8083/uimcardprj/share/meun.jsp var curWwwPath=window.document.location.href; / / after the access to the host address directory, such as: uimcardprj/share/meun JSP var pathName = window. The document. The location. The pathName; var pos=curWwwPath.indexOf(pathName); // Obtain the host address, for example: http://localhost:8083 var localhostPaht= curwwwpath. substring(0,pos); /uimcardprj var projectName= pathname.substring (0, pathname.substr (1).indexof ('/')+1); /uimcardprj var projectName= pathname.substring (0, pathname.substr (1).indexof ('/')+1); return(localhostPaht+projectName); }Copy the code
JS judge the decimal point after a few
num.toString().split(".")[1].length
JS intercepts the number to N decimal places
- using
math.round
Var result = math.round (original*100)/100; Var result = math.round (original*10)/10; / / returns 28.5Copy the code
- using
toFixed
Var result=original.toFixed(2); Var result=original. ToFixed (1); / / returns 28.5Copy the code
JS controls the Input number and two decimal places
function clearNoNum(value) { value = value.replace(/[^\d.]/g, ""); // Clear "number" and "." Replace (/\.{2,}/g, "."); // Keep only the first one. Remove excess value = value. The replace (". ", "$# $"). The replace (/ \. J/g," "). The replace (" $# $", ""); value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); If (value.indexof (".") < 0 && value! = "") {// float (value) = parseFloat(value); }}Copy the code
JS verify the phone number and landline number method
The function $isPhoneAvailable (STR) {let isMob = / ^ [1] [3,4,5,6,7,8,9] [0-9] {9} $/; Let isPhone = / ^ ([0-9] {3, 4} -)? [0-9] {7, 8} $/; if (isPhone.test(str) || isMob.test(str)) { return true; }else { return false; }}Copy the code
JS indexOf() is case-insensitive
- use
str.toLowerCase()
orstr.toUpperCase()
Convert all the comparison strings to large (small) writes
How does JS replace() replace keys
Str.replace (new RegExp(' keyword to be replaced ','g'), '
)
Past oliver
Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future
Read on to make your interviewer fall in love with you
Remember a painful experience
Front-end performance optimization -HTML, CSS, JS parts
Front-end performance optimization – Page loading speed optimization
Front-end performance optimization – Network transport layer optimization