比较cookie的值每次都返回“false”

时间:2016-08-30 09:43:56

标签: javascript cookies string-comparison if-case

我有一个名为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部分。

1 个答案:

答案 0 :(得分:1)

我查了console.log(typeof(foo)); 并且不知何故它是一个对象,这就是为什么我的字符串比较返回“false”。