温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

为什么不需要在JavaScript使用switch 语句!

发布时间:2021-09-30 15:10:02 来源:亿速云 阅读:172 作者:柒染 栏目:web开发

本篇文章为大家展示了为什么不需要在JavaScript使用switch 语句!,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

没有 switch 就没有复杂的代码块

switch很方便:给定一个表达式,我们可以检查它是否与一堆case子句中的其他表达式匹配。考虑以下示例:

const name = "Juliana";  switch (name) {   case "Juliana":     console.log("She's Juliana");     break;   case "Tom":     console.log("She's not Juliana");     break; }

当 name 为**“Juliana”**时,我们将打印一条消息,并立即中断退出该块。在switch函数内部时,直接在 case 块使用  return,就可以省略break。

当没有匹配项时,可以使用 default 选项:

const name = "Kris";  switch (name) {   case "Juliana":     console.log("She's Juliana");     break;   case "Tom":     console.log("She's not Juliana");     break;   default:     console.log("Sorry, no match"); }

switch在 Redux reducers 中也大量使用(尽管Redux Toolkit简化了样板),以避免产生大量的if。考虑以下示例:

const LOGIN_SUCCESS = "LOGIN_SUCCESS"; const LOGIN_FAILED = "LOGIN_FAILED";  const authState = {   token: "",   error: "", };  function authReducer(state = authState, action) {   switch (action.type) {     case LOGIN_SUCCESS:       return { ...state, token: action.payload };     case LOGIN_FAILED:       return { ...state, error: action.payload };     default:       return state;   } }

这有什么问题吗?几乎没有。但是有没有更好的选择呢?

从 Python 获得的启示

来自 Telmo 的这条  Tweet引起了我的注意。他展示了两种“switch”风格,其中一种非常接近Python中的模式。

Python 没有开关,它给我们一个更好的替代方法。首先让我们将代码从 JavaScript 移植到Python:

LOGIN_SUCCESS = "LOGIN_SUCCESS" LOGIN_FAILED = "LOGIN_FAILED"  auth_state = {"token": "", "error": ""}   def auth_reducer(state=auth_state, action={}):     mapping = {         LOGIN_SUCCESS: {**state, "token": action["payload"]},         LOGIN_FAILED: {**state, "error": action["payload"]},     }      return mapping.get(action["type"], state)

在 Python 中,我们可以使用字典来模拟switch 。dict.get() 可以用来表示 switch的 default 语句。

当访问不存在的key时,Python 会触发一个 KeyError 错误:

>>> my_dict = {     "name": "John",      "city": "Rome",      "age": 44     }  >>> my_dict["not_here"]  # Output: KeyError: 'not_here'

.get()方法是一种更安全方法,因为它不会引发错误,并且可以为不存在的key指定默认值:

>>> my_dict = {     "name": "John",      "city": "Rome",      "age": 44     }  >>> my_dict.get("not_here", "not found")  # Output: 'not found'

因此,Pytho n中的这一行:

return mapping.get(action["type"], state)

等价于 JavaScript中的:

function authReducer(state = authState, action) {   ...     default:       return state;   ... }

使用字典的方式替换 switch

再次思考前面的示例:

const LOGIN_SUCCESS = "LOGIN_SUCCESS"; const LOGIN_FAILED = "LOGIN_FAILED";  const authState = {   token: "",   error: "", };  function authReducer(state = authState, action) {   switch (action.type) {     case LOGIN_SUCCESS:       return { ...state, token: action.payload };     case LOGIN_FAILED:       return { ...state, error: action.payload };     default:       return state;   } }

如果不使用 switch 我们可以这样做:

function authReducer(state = authState, action) {   const mapping = {     [LOGIN_SUCCESS]: { ...state, token: action.payload },     [LOGIN_FAILED]: { ...state, error: action.payload }   };    return mapping[action.type] || state; }

这里我们使用 ES6 中的计算属性,此处,mapping的属性是根据两个常量即时计算的:LOGIN_SUCCESS 和  LOGIN_FAILED。属性对应的值,我们这里使用的是对象解构,这里 ES9((ECMAScript 2018)) 出来的。

const mapping = {   [LOGIN_SUCCESS]: { ...state, token: action.payload },   [LOGIN_FAILED]: { ...state, error: action.payload } }

你如何看待这种方法?它对 switch 来说可能还能一些限制,但对于 reducer 来说可能是一种更好的方案。

但是,此代码的性能如何?

性能怎么样?

switch 的性能优于字典的写法。我们可以使用下面的事例测试一下:

console.time("sample"); for (let i = 0; i < 2000000; i++) {   const nextState = authReducer(authState, {     type: LOGIN_SUCCESS,     payload: "some_token"   }); } console.timeEnd("sample");

测量它们十次左右,

for t in {1..10}; do node switch.js >> switch.txt;done for t in {1..10}; do node map.js >> map.txt;done

上述内容就是为什么不需要在JavaScript使用switch 语句!,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI