You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何精简并合并JS Cookie判断与获取函数?

Hey there! Let's clean up those cookie functions—they share almost identical logic, so merging them into a single, streamlined method makes perfect sense. Here's a polished, modern take that handles both checking existence and retrieving values:

Optimized Single Method

function getCookie(cookieName, checkOnly = false) {
  // Split and clean up cookie string into valid key-value pairs
  const cookiePairs = document.cookie.split(';')
    .map(pair => pair.trim())
    .filter(pair => pair.length > 0);

  // Find the cookie matching our target name
  const matchingCookie = cookiePairs.find(pair => pair.startsWith(`${cookieName}=`));

  if (!matchingCookie) {
    return checkOnly ? false : null;
  }

  return checkOnly ? true : matchingCookie.split('=')[1];
}

Key Improvements & How to Use

  • Eliminated Duplication: No more repeating the cookie splitting/cleanup logic across two functions.
  • Modern JS Syntax: Uses map, filter, and find for cleaner, more readable iteration (instead of clunky for loops).
  • Flexible Behavior:
    • To check if a cookie exists: Call getCookie('yourCookieName', true) — returns true or false.
    • To retrieve the cookie's value: Call getCookie('yourCookieName') — returns the value (or null if it doesn't exist).
  • Cleaner Trimming: Uses native trim() instead of a regex for removing whitespace (works in all modern browsers).

If you need to support super old browsers (like IE8), you can swap trim() with your original regex, and add a polyfill for Array.prototype.find—but for most projects today, this version is totally solid.

内容的提问来源于stack exchange,提问作者user1060990

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:47:54