Using object mapping instead of if-else in js can be very elegant!

No one likes a bunch of monotonous ifelse, is there a more elegant way? That's jojo 对象映射 !

example:

//常见if-else组成的逻辑判断
FnAll(code, p){
	if(code === 'a'){
		Fna(p);
	}
	if(code === 'b'){
		Fnb(p);
	}if(code === 'b'){
		Fnc(p);
	}if(code === 'd'){
		Fnd(p);
	}
	......
}

Such a stud is certainly not cool, it is perfect.
Insert picture description here
Let's try using object mapping

//定义一个方法对象
const FnProject = {
	Fna(p),
	Fnb(p),
	Fnc(p),
	Fnd(p)
}
//调用
FnAll(data , p){
	FnProject[data](p)
}

Doesn't it look concise, can it be installed with X, is it beautiful?
Insert picture description here

Published 113 original articles · praised 33 · 40,000+ views

Guess you like

Origin blog.csdn.net/qq_40282732/article/details/105687692