This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

1. Simpleif elseThe shorthand

When we only have one level of if judgment, we can abbreviate this conditional judgment

/ / the original
let id = this.id
if(id === 'xxxxxx') {this.flag = true
}else{
	this.flag = false
}
// The above method can be abbreviated as
this.flag = (id === 'xxxxxx')?true : false
Copy the code

2. Judge the null value.null.nudefined

Sometimes, we need to determine if a value is null so that we can proceed to the next step; Or check if the entered value is null.

/ / the original
let input = this.value
if(input === null || input === undefined || input === "") {this.flag = false
}else{
	this.flag = true
}
/ / short
this.flag = true || ""
Copy the code

3. Boolean value judgment

We’re just trying to determine the Boolean value of a variable to operate on.

/ / the original
if(flag === true) {}/ / short
if(flag)
Copy the code

4, circulation

Looping is one of the most common methods we use when dealing with data

for(var i=0; i<list.length; i++)for (let i in list)

for(let i of list)

list.forEach(item= >{})
Copy the code

5. Intertransformation of strings and numbers

We’re going to change some of the numeric strings that are returned from the back end to numeric values, so we can do calculations and things like that. The value also needs to be converted to a string because the field type required by the back end is a string.

let string = '123'
let number = 123
// Turn the string to a value
let num1 = string*1  // This is the simplest, but can only be numeric strings
let num2 = parseInt(string);  // This is 123 converted to an integer; Or extract numbers from a concatenation of numbers and characters
let num3 = parseFloat(string);  // This is the precision conversion, 123.0
let num4 = Number(string) // This is mandatory conversion

// Convert the string
let s = number.toString()
let s2 = number+""

// Enter a maximum of two decimal digits in the input box, and change the units
let amout=(this.ruleForm.amount)*100
this.ruleForm.amount = (parseFloat(amout)).toString()  // So there is no loss of precision
Copy the code

6, string interception, splicing

To some strings to intercept, and then spliced into their own data needs

Substr (" Where to start "," How many ")
let string = 'obj_open123456789'
string.substr(3.5)
string.substr(3) // return everything after the third bit
//split
let obj = string.split('_');
let id = 'user_'+obj
//substring(3)
let a = string.substring(3)

// Intercept data from behind
let type = (file.name).substring((file.name).lastIndexOf(".") +1)
Copy the code

7. Check whether the string contains a character

Determines whether the string contains a particular character

// Check whether a string contains a return subscript but does not contain a return -1
let string = 'obj_open123456789'
var i = string.indexOf("open")
Copy the code

8, the simplification of judgment conditions more

This is a query containing a method that can be used to do multiple value judgments; For example, when determining whether the type of file uploaded is correct

let type = file.type
/ / the original
if (type === 'png' || type === 'jpg' || type === 'jpeg' || type ==='svg') {}
/ / now,
if(['png'.'jpg'.'jpeg'.'svg'].includes(type)){}
/ / or
if(['png'.'jpg'.'jpeg'.'svg'].indexOf(type) >= 0) {}Copy the code

9. Multivariable assignment

Assign values to multiple variables at the same time

let a= 1
let b = 2
let c= 3
/ / short
let [a,b,c] = [1.2.3]

/ / or
let x;
let y = true
let x,y=true
Copy the code

Empty the array with length

let arr = [1.2.3.4.5]
arr,length = 0
let arr = []
Copy the code

Void merge operator

Whenever we need to check whether a value is null, we add a default value to the null value

/ / the original
if(str === ' ') {this.flag = 'long term'
}
/ / short
this.flag = null ?? 'long term'
Copy the code

12. Merge arrays

Concat, which creates a new array and concatenates the array with any array or value.

let arr = ['1'.'2'.'3'.'4']
let arr2 = ['9']
let arr3 = arr.concat(arr2)
console.log(arr3);
//['1', '2', '3', '4', '9']
Copy the code

13. Check whether a field exists in the object

if('role_info' in obj){}
Copy the code

14. Obtain random numbers within a specified range

In development, we may need to use some randomly generated field values

let num = Math.floor(Math.random() * (max - min + 1)) + min;
Copy the code

15. Keep decimals

let num =2.123456;
num = num.toFixed(2);  // This value will be rounded to 2.12
// If you don't want to be rounded
let num2 = parseFloat((num * 100) /100) // 

// Other methods
parseInt(num)  // only round 2
Math.ceil(num) // Round up. If there is a decimal, add 1 to the whole number
Math.floor(num) // round down
Math.floor(num)  // Round off
Copy the code

16. Change the key sum of an object to a numeric value

let obj={id:1.res:true.msg:error}
// Turn the key of the object into an array
Object.keys(obj) //['id','res','msg']

// Turn the value of the object into an array
Object.values(obj) // [1,true,error]

// gets the key and value of the object and returns a multidimensional array
Object.entries(obj) // [['id',1],['res',true],['msg',error]]
Copy the code

17, determine whether there are specific characters in the string, checkhttp

let html = (this.html).trim().toLowerCase() // Change it to lowercase
console.log(html.indexOf('http') = ='1');  // Check whether the URL contains HTTP
Copy the code

Check if there are any specific characters in the array

let text = ['TXT'.'DOC'.'XLS'.'PPT'.'DOCX'.'XLSX'.'PPTX'.'pdf'.'txt'.'doc'.'xls'.'ppt'.'docx'.'xlsx'.'pptx'.'zip'.'rar'.'ZIP'.'RAR'] text.indexof (type) if = -1The character is not in the array,Copy the code

19. Change the string to lowercase

let type2 = type.trim().toLowerCase()
Copy the code

Time format conversion and time acquisition

var myDate = new Date(a); myDate.getYear();// Get the current year (2 bits)
myDate.getFullYear(); // Get the full year (4 bits,1970-????)
myDate.getMonth(); GetMonth ()+1; myDate.getMonth()+1;
myDate.getDate(); // Get the current day (1-31)
myDate.getDay(); // Get the current week X(0-6,0 for Sunday)
myDate.getTime(); // Get the current time (milliseconds from 1970.1.1)
myDate.getHours(); // Get the current hour (0-23)
myDate.getMinutes(); // Get the current minute (0-59)
myDate.getSeconds(); // Get the current number of seconds (0-59)
myDate.getMilliseconds(); // Get the current number of milliseconds (0-999)
myDate.toLocaleDateString(); // Get the current date
var mytime=myDate.toLocaleTimeString(); // Get the current time
myDate.toLocaleString( ); // Get the date and time
Copy the code

21,JSGet the current timestamp method –JavaScript There are three ways to get the current millisecond timestamp

var timestamp =Date.parse(new Date()); Results:1280977330000       // Not recommended; Milliseconds changed to 000 display

var timestamp =(new Date()).valueOf(); Results:1280977330748       / / recommended;

var timestamp=new Date().getTime(); Results:1280977330748        / / recommended;.jsnew Date(a); Display the format Mar31 10:10:43 UTC+0800 2012But the use ofnew Date() Participation is automatically converted to slave1970.11.The number of milliseconds to startCopy the code

Please feel free to discuss in the comments section. The nuggets will draw 100 nuggets in the comments section after the diggnation project. See the event article for details