Several simple js optimization methods

1. Reduce if...else code

const getData = (data)=>{
    
    
	if(data == 1){
    
    
		return '开心'
	}else if(data == 2){
    
    
		return '生气'
	}..........
}
console.log(getData(1))

We can optimize it like this

const dataList = {
    
    
	1:'开心'2:'生气'3:'郁闷'
}
const getData = (name)=>{
    
    
	return dataList[name]
}
console.log(getData(1))

2. Pipeline operations replace redundant loops.
How do we find out the name whose type is 1?

const dataList =[
{
    
    name:'开心1',type:'1'},
{
    
    name:'生气',type:'2'},
{
    
    name:'开心2',type:'1'},
{
    
    name:'开心3',type:'1'}
]

is it going to be like this

let names = [];
for(let i=0;i<dataList.length;i++){
    
    
if(dataList[i].type === 1){
    
    
names.push(dataList[i].name)
}
}

Why don't we try this
1. Filter first and then recombine

let names = [];
let names = dataList.filter(i=>i.type === 1).map(i=>i.name)
console.log(names)

find replaces redundant loops
or the above data we need to find out the specific type name, the usefulness of find comes out

const findName = (list,name,type)=>{
    
    
	for(let i=0;i<list.length;i++){
    
    
		if(list[i].type === type && list[i].name === name){
    
    
			return list[i]
		}
	}
}

Let's take a look at find

const newData = dataList.find(i => i.name === '表情1' && i.type === 1);
console.log(newData)

includes replaces redundant loops
1. Take the old sauerkraut as an example, it contains sauerkraut noodles, beef, cigarette butts and foot skin

const instantNoodles = [ '酸菜', '面', '牛肉粒', '烟头', '脚皮']
let foot = false;
for(let i=0;i<instantNoodles.length;++i){
    
    
if(instantNoodles[i] == '脚皮'){
    
    
		foot = true
}
}
//我们可以用includes
const foot = instantNoodles.includes('脚皮');
console.log(foot)

result return value

const getUrl(content,prefix,suffix)=>{
    
    
	let result = content;
	if(prefix){
    
    
		result = `${
      
      prefix}${
      
      result}`
	}
	if(suffix){
    
    
		result = `${
      
      result}${
      
      suffix}`
	}
	return result
}
console.log(getUrl('www.baidu.com','https://','.cn'))

 
	

Guess you like

Origin blog.csdn.net/weixin_41688609/article/details/123865030