我有一个名为getCookie(x)
的函数,它返回名称为x
的cookie的值。
当我使用console.log(getCookie(foo));
检查时,如果cookie不存在,则返回正确的solved
术语或空字符串。 Foo
是一个变量!
对于此测试,我的Cookie foo
存在且值为"solved"
但如果我这样做:
console.log(getCookie(foo) == "solved");
它返回false。这是为什么?
这是我的getCookie()
功能:
function getCookie(cname){
var name = cname + "=";
var carray = document.cookie.split(";");
for(var j=0; j <carray.length; j++){
var cookie = carray[j];
while(cookie.charAt(0)==" "){
cookie = cookie.substring(1);
}
if (cookie.indexOf(name) == 0){
return cookie.substring(name.length,cookie.length); //retruns the value of the cookie, in my case it is always "solved"
}
}
return ""; //if there is no cookie with the given name, it returns an empty string
}
我删除了评论,因为它们不是英文版。我的cookie也有一个过期日期,这就是为什么我必须做这些“狂野”的事情来获得cookiename=value
部分。
答案 0 :(得分:1)
我查了console.log(typeof(foo));
并且不知何故它是一个对象,这就是为什么我的字符串比较返回“false”。