你可能不需要在JavaScript使用switch语句

作者:状态漫游时间:2026-10-24 09:57:03浏览:636

本文探讨JavaScript中switch语句的替代方案,重点介绍利用对象字典映射简化Redux reducer逻辑。通过对比Python的字典get方法,展示如何使用计算属性构建更简洁的状态处理函数,并附带实际性能测试结果,分析两种写法的执行效率差异。

避免使用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”时,程序会打印一条消息,并立即通过break退出该代码块。如果在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-else判断。参考以下示例:


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的一条推文引起了我的注意。他展示了两种“switch”风格的写法,其中一种非常接近Python中的模式匹配。

Python没有switch语句,但它提供了一个更好的替代方案。首先,让我们将代码从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'

因此,Python中的这一行:


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语句的详细内容,更多关于JavaScript switch语句的资料请关注本站其它相关文章!

作者最新文章