Files
onixbyte.com/docs/zh-hans/blogs/ecmascript-2025-syntax-sugar.md
T
zihluwang 861852961f style: format the repository with prettier
These files were already out of step with the project's Prettier config
before this branch of work; running `pnpm format` finally swept them up.
No semantic changes.

Kept separate from the functional commits so the reformatting does not
bury them in diff noise.
2026-09-25 15:37:59 +08:00

1.3 KiB

title, tags, author
title tags author
ECMAScript 2025 语法糖大全
javascript
ecmascript
pattern-matching
frontend
name email
Zihlu Wang real@zihluwang.me

模式匹配

传统写法

function processResponse(response) {
  if (response.status === 200 && response.data) {
    return { success: true, data: response.data }
  } else if (response.status === 404) {
    return { success: false, error: "Not found" }
  } else if (response.status >= 500) {
    return { success: false, error: "Server error" }
  } else {
    return { success: false, error: "Unknown error" }
  }
}

模式匹配写法

function processResponse(response) {
  return match (response) {
    when ({ status: 200, data }) -> ({ success: true, data })
    when ({ status: 404 }) -> ({ success: false, error: 'Not found' })
    when ({ status: status if status >= 500 }) -> ({ success: false, error: 'Server error' })
    default -> ({ success: false, error: 'Unknown error' })
  };
}

数组长度分支也能优雅处理

function handleArray(arr) {
  return match (arr) {
    when ([]) -> "Empty array"
    when ([first]) -> `Only one element: ${first}`
    when ([first, second]) -> `Two elements: ${first}, ${second}`
    when ([first, ...rest]) -> `First element: ${first}, others: ${rest.length} items`
  };
}