1.switch-case
function translateState(state) {
switch (state) {
case "published":
state = "success";
break;
case "draft":
state = "gray";
break;
case "deleted":
state = "danger";
break;
default: //default可以省略,并不是每个switch都有default
}
return state;
}
console.log(translateState('published'))
注意:1.switch-case匹配用的是全等,所以值相等并且类型相等才能成功匹配
2.从某一个case进入语句,如果没有遇到break,那么代码会继续执行下面的case,直到遇见break结束。如果一个break都没有,那么就会把整个switch语句后面的全部执行完,包括default(cae穿透)
2.对象
function statusFilter(status) { const statusMap = { published: "success", draft: "gray", deleted: "danger" }; return statusMap[status]; } console.log(statusFilter('published')) //success