JavaScript Cookie 读取问题:解决 undefined 错误

这段代码中,变量名 cookies.notoce 中的 . 可能是一个错误,应该改为 cookies["notoce"] 才能正确获取到 cookie 中的值。另外,如果获取到的值为空,也会输出 undefined。因此,可以在输出前先判断一下值是否为空,如下所示:

var noticeStr = decodeURIComponent(cookies["notoce"]);
notimsg = noticeStr.replace(/[[]"]+/g, "");

if (notimsg) {
  layer.msg(notimsg, function(){});
  console.log(notimsg);
} else {
  console.log("获取 cookie 值失败!");
}

解释:

  1. cookies.notoce 错误: JavaScript 中使用 . 来访问对象的属性,但如果属性名称包含特殊字符(如 -、_、数字),则需要使用 [] 来访问。因此,应该将 cookies.notoce 改为 cookies["notoce"]。
  2. 值为空: 如果 Cookie 中没有名为 notoce 的值,cookies["notoce"] 将返回 undefined,导致输出错误。因此,在输出前需要判断 notimsg 是否为空。

总结:

出现 “undefined” 错误的原因可能是 Cookie 名字使用错误或 Cookie 值为空。使用 [] 访问属性和判断值是否为空可以有效解决此问题。

JavaScript Cookie 读取问题:解决 undefined 错误

原文地址: https://www.cveoy.top/t/topic/lQ3Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录