如何精简并合并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, andfindfor cleaner, more readable iteration (instead of clunky for loops). - Flexible Behavior:
- To check if a cookie exists: Call
getCookie('yourCookieName', true)— returnstrueorfalse. - To retrieve the cookie's value: Call
getCookie('yourCookieName')— returns the value (ornullif it doesn't exist).
- To check if a cookie exists: Call
- 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
相关产品推荐
相关产品推荐

