为什么这个数字是一个字符串?

Ada*_*dam 2 javascript cookies jquery typeof

使用jQuery Cookies插件,我正在设置一个cookie,其值是一个数字.

$.cookie('xyz_id','1');
Run Code Online (Sandbox Code Playgroud)

我需要使用这个数字来获取HTML中元素的索引.

var $curr = $.cookie('xyz_id'); 
var $el = $('#main li:eq($curr)');
Run Code Online (Sandbox Code Playgroud)

$ curr的输出是1.那么为什么typeOf()$ curr显示为字符串而不是数字?我尝试使用parseInt()将其转换为数字失败了.不知道发生了什么......

Jar*_*ish 10

引号使变量成为字符串:

'1'
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,cookie实际上是字符串:

要读出cookie,您必须将document.cookie视为字符串并搜索某些字符(例如分号)和cookie名称.

http://www.quirksmode.org/js/cookies.html

相反,做:

$.cookie('xyz_id', 1); // or, really, '1' would be the same
Run Code Online (Sandbox Code Playgroud)

然后,当读回值时,使用将其强制转换为数值parseInt().

var xyz_id = parseInt($.cookie('xyz_id'));
Run Code Online (Sandbox Code Playgroud)

哪个应该创建一个数值.

此外,parseInt应该(在合理范围内)对字符串中的数字进行类型转换.看到:

var i = "1";
alert(typeof i);
i = parseInt(i);
alert(typeof i);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/CqBw6/