Summary of js practical tips

Summary of js practical tips

Record the js skills used in actual combat development


One, string, number

1. Determine how many decimal places the string (number) has

The code is as follows (example):

let x = String(value).indexOf('.')+1//小数点的位置
let y = String(value).length - x   //有几位小数

2. Limit input to only numbers

The code is as follows (react):

changeEvent=(e)=>{
    
    
    let value = e.target.value.replace(/[^\d]/, '')
    this.setState({
    
     checkCode: value })
}
 <input value={
    
    this.state.checkCode}
 	    onChange={
    
    (e) => this.changeEvent(e)>
</input>
//[^\d]表示所有除了数字以外的字符,/g表示全局匹配,
//.replace(/[^\d.]/g,"")表示将数字以外的字符替换为空

3. Number rounding

1、只取整数
parseInt(5/2)    // 2,丢弃小数部分,只保留整数部分
2.向上取整
Math.ceil(5/2)   // 3,有小数就整数部分加1
3.向下取整
Math.floor(5/2)  // 2,丢弃小数部分
4.四舍五入
Math.round(5/2)  // 3,四舍五入

Second, the array

1. JS deletes the first element of the array

The code is as follows (example):

arr=['George','John','Thomas']
a = arr.shift() 
//得到=》a='George'  ,arr=['John','Thomas']
//.shift() 方法用于把数组的第一个元素从其中删除,改变了原来的数组,并返回第一个元素的值
//.pop()用法和.shift()一样,把数组最后一个元素从其中删除

2. The use of "magical oil" splice()

①Change the value of the original array without returning any value, and realize the deletion, insertion, and replacement of the array.
②The first parameter is the starting index, the second parameter is how many to replace, and the third parameter is the
code to replace. As follows (example):

插入:
var arr = ['a','b','c','d'];
arr.splice(1,0,'ttt');//第二个参数为0,代表不替换任何值     
//得到=》arr=['a','ttt','b','c','d'] 
替换:
var arr = ['a','b','c','d'];
arr.splice(1,2,'ttt');//第二个参数为2,代表替换掉两个值
console.log(arr);        
//得到=》arr=['a','ttt','c','d'] 
删除:
var arr = ['a','b','c','d'];
arr.splice(1,2);
//arr=['a','d']; 

3. Concat() connect two or more arrays

The code is as follows (example):

let a = [1,2,3];
let b = a.concat([4,5])
// 得到=>b=[1,2,3,4,5],不改变a;

Reminder: Long-term article updates...

Guess you like

Origin blog.csdn.net/weixin_44745920/article/details/109719854