前言
假设现在我需要设计一个判断方法,根据传入的字符串返回对应的结果。
首先想到的应该是 if else 或者 switch。
例如:
// 判断不同的请求方法
const getMethod = (method: string) => {
if (method === "get") return GET();
if (method === "post") return POST();
if (method === "patch") return PATCH();
if (method === "delete") return DELETE();
};
switch就不写了。
看上去我们要写很多的 if 或 if else,有一些繁琐。
但我们可以根据对象的字符串索引特性来重构上面的代码。如下:
const getMethod = (method: string) =>({
get: GET(),
post: POST(),
patch: PATCH(),
delete: DELETE(),
}[method]);
这样看上去代码就简洁、易读很多。
碎碎念:在一个对象中访问不存在的属性返回的是undefined,不会报错。
也就是说不用加上|| undefined也是安全的。