前端网络请求回调中经常会根据后端返回的不同 code 进行不同的业务处理。
if (res.data.code === "0000") {
//do something
} else if (res.data.code === "0001") {
//do something
} else if (res.data.code === "0002") {
//do something
} else {
//do something
}
简单应用
const statusCode = new Map([
["0000", "请求成功"],
["0001", "未授权"],
["0002", "拒绝访问"],
]);
statusCode.get(0001);
复杂业务函数处理
const getRequest = (params) => {
console.log("请求打印");
};
const statusCode = new Map([
[
"0000",
async (params) => {
console.log(getRequest(params));
},
],
[
"0001",
(params) => {
console.log("未授权");
},
],
[
"0002",
(params) => {
console.log("拒绝访问");
},
],
]);
const params = {};
const showMessage = (code) => {
// Map 对象转数组
[...statusCode].forEach(([key, value]) => {
key === code ? value.call(params) : "";
});
};
showMessage("0000"); // 未授权
forEach()
和 map()
的区别:
forEach()
会修改原来的数组,而map()
会得到一个新的数组并返回。所以需要生成新数组的时候,就用后者, 否则就用前者。
Map vs Object
-
According to MDN:
A Map object can iterate its elements in insertion order - a for..of loop will return an array of [key, value] for each iteration.
Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this, Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better.
An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null). The keys of an Object are Strings, where they can be any value for a Map. You can get the size of a Map easily while you have to manually keep track of size for an Object.