JS 一元判斷語句優化以及eval用法
阿新 • • 發佈:2018-11-19
在網上看到了 if else if 多條語句判斷的優雅寫法,如下所示:
var processMsg = function (type) { if("Next" === type){ processMedia("next"); }else if("Previous" === type){ processMedia("previous"); }else if("Stop" === type){ processMedia("stop"); }else if("Pause" === type){ processMedia("pause"); }else if("Play" === type){ processMedia("play"); }else{ console.log("the type is not supported: " + type); } };
用switch case看上去比較整潔,另外如果不同的type 可能處理的函式是一樣的。
var processMsg = function (type) { switch (type){ case "Next": processMedia("next"); break; case "Previous": processMedia("previous"); break; case "Stop": processMedia("stop"); break; case "Pause": processMedia("pause"); break; case "Play": processMedia("play"); break; default: console.log("the type is not supported: " + type); break } };
這種就看上去好多了。
var processMsg = function (type) { var actions = { "Next" : "next", "Previous" : "previous", "Stop" : "stop", "Pause" : "pause", "Play" : "play" }; var action = actions[type]; !!action ? processMedia(action) : console.log("the type is not supported: " + type); };
但還有一種情況是這樣的:
var processMsg = function (type) { if("Next" === type){ processNext(); }else if("Previous" === type){ processPrevious(); }else if("Stop" === type){ processStop(); }else if("Pause" === type){ processPause(); }else if("Play" === type){ processPlay(); }else{ console.log("the type is not supported: " + type); } };
那麼eval函式就派上用場了:
var processMsg = function (type) { var actions = { "Next" : "Next", "Previous" : "Previous", "Stop" : "Stop", "Pause" : "Pause", "Play" : "Play" }; var action = actions[type]; !!action ? eval("process" + action + "()") : console.log("the type is not supported: " + type); };