js代码优化及常用代码(持续更新……)

本文介绍了JavaScript中的一些实用技巧,如保留两位小数的精确处理、解构赋值提高代码效率、使用includes方法检查元素、数组去重、reduce函数的应用,以及按属性对对象和数组进行分组。
摘要由CSDN通过智能技术生成


1.保留两位小数,不够两位数不补0

let num1 = 111
console.log(parseFloat(num1.toFixed(2))) //111
//不够两位数不补0
let num2 = 111.1
console.log(parseFloat(num1.toFixed(2))) //111.1
//补0
console.log(num1.toFixed(2)) //111.10
let num3 = 111.12
console.log(parseFloat(num1.toFixed(2))) //111.12
let num4 = 111.123
console.log(parseFloat(num1.toFixed(2))) //111.12

2.解构赋值

2.1 提取数据

const name= this.options.userName
const phone= this.options.userPhone
const address = this.options.address 

//优化后
const {userName:name,userPhone:phone,address } = this.options

2.2 交换变量值

let a = 2
let b = 3
[a,b] = [b,a]

3.includes

includes用于检查数组或字符串中是否包含特定元素的方法

3.1 多个if条件优化

if(name === 'test1' || name === 'test2' || name === 'test3'|| name === 'test4'){}

//优化后
if(['test1','test2','test3','test4'].includes(name)){}

3.2 判断数组对象中是否有某值

let arr = [
    {name:'Miruna'},
    {city:'shanghai'},
    {time:'2024'}
]
console.log(arr.some(obj=>Object.values(obj).includes('2026')))		//false
console.log(arr.some(obj=>Object.values(obj).includes('2024')))		//true

3.3 判断二维数组中是否有某值

let plants = [[2,3,6,8],[4,5,8,9],[5,9,10,12]]
console.log(plants.flat().includes(5))		//true
console.log(plants.flat().includes(20))		//false

4. null、undefined、空值检查

if(a != undefined || a != null){
	b = a
}

//优化后
b = a || ''
//或者
b = a ?? ''

?? 和 ||区别:??左侧值为nullundefined才会取右边的值;而||,左侧值为nullundefinedfalse0NaN'' 时会取右边的值。
?.只判断左侧值为null时取右侧的值

5.数组去重

const myArray = ["a", "b", "a", "b", "c", "e", "e", "c", "d", "d", "d", "d"]
//实现返回['a', 'b', 'c', 'e', 'd']

//1.filter
const filterArray = myArray.filter((value,index,self)=>{
	return self.indexOf(value) === index
})

// 2.reduce+includes
const reduceArray = myArray.reduce((acc,cur)=>{
	if(!acc.includes(cur))return [...acc,cur]
	return acc
},[])

//3.set
const setArry=[...new Set(myArray)]

6. 去除数组对象中的重复值

const demo = [
    { value: "001", label: "aaa" },
    { value: "001", label: "bbb" },
    { value: "002", label: "aaa" },
    { value: "002", label: "aaa" },
]
//实现:[
//    {"value": "001","label": "aaa"},
//    {"value": "001","label": "bbb"},
//    {"value": "002","label": "aaa"}]

//1.filter
const result1 = demo.filter((obj,index,self)=>{
	return index === self.findIndex(item=>item.value === obj.value && item.label=== obj.label)
})

//2.reduce
const result2 = demo.reduce((acc,cur)=>{
	let sameList = acc.some(item=>item.value === cur.value && item.label === cur.label)
	if (!sameList) acc.push(cur)
	return acc
},[])

//3.map
const map = new Map()
demo.forEach((obj)=>map.set(JSON.stringify(obj),obj))
const result3 = [...map.values()]

7.reduce

7.1统计值出现的次数

const colorArr = ["red","blue","red","pink","red"]

const result= colorArr.reduce((accumulator,currentValue)=>{
	const current =  accumulator[currentValue] ?? 0
	return {
		...accumulator,
		[currentValue]: current+ 1
	}
},{})
// {'red':3,'blue':1,'pink':1}

7.2.按属性对对象进行分组

const colorArr = [
	{color:'red',id:1},
	{color:'blue',id:2},
	{color:'pink',id:2},
]

const groupColor = colorArr.reduce((acc,cur)=>{
    const key = cur['id']
    const curGroup = acc[key] ?? []
    return{
    	...acc,
        [key]:[...curGroup,cur]
    }
},{})
// {
//   1: [{ color:'red',id:1 }],
//   2: [
//     {color:'blue',id:2},
//	   {color:'pink',id:2}
//   ]
// }

7.3按属性对数组进行分组

const arr =  [
    { province:'湖南',
     city:'长沙'
    },
    { province:'湖南',
     city:'岳阳'
    },
    { province:'上海',
     city:'浦东'
    }
]
 const result = arr.reduce((acc,cur)=>{
 	let sameList = acc.find(item=>item.value === cur.province)
 	if(!sameList){
 		acc.push({
 			value:cur.province,
 			children:[cur.city]
 		})
 	}else{
 		sameList.children.push(cur.city)
 	}
 	return acc
 },[])   
 //[
//     {
//         value:'湖南',
//         children:['长沙','岳阳']
//     },
//     {
//         value:'上海',
//         children:['浦东']
//     }
// ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值