乐趣区

关于javascript:获取cookie的值设置cookie删除cookie

获取 cookie 的值,设置 cookie,删除 cookie

对于更多日常应用的公共类的操作方法,能够关注下小滑轮网站 http://www.feiaci.com/#/self/…

/**
 * 获取 cookie 里的值
 * @param {String} key
 */
export const getCookie = (key) => {const arr = document.cookie.match(new RegExp(`(^|)${key}=([^;]*)(;|$)`));
  if (arr != null) return unescape(arr[2]);
  return null;
}

/**
 * 设置 cookie
 * @param name
 * @param value
 * @param day expires 的工夫
 */
function setCookie (name, value, day) {let setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){for (let i in setting) {let oDate = new Date();
            oDate.setDate(oDate.getDate() + day);
            document.cookie = i + '=' + setting[i] + ';expires=' + oDate;
        }
    }else{let oDate = new Date();
        oDate.setDate(oDate.getDate() + day);
        document.cookie = name + '=' + value + ';expires=' + oDate;
    }

}

/** 
 * 删除 cookie
 */
function removeCookie (name) {setCookie(name, 1, -1);
}
退出移动版