获取cookie值为整数

时间:2017-08-07 21:48:26

标签: javascript cookies

主要问题是,当打印cookie值时,它会在它周围添加引号,但在我的情况下,我需要它打印的数字不是字符串。

这是功能:

function getCookie(cname) {
    var name = cname + '=';
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return '';
}

例如,假设在Get Cookie之前,我设置了一个像这样的cookie:

function setCookie(cname, value) {
        document.cookie = cname + '=' + value + ';' + ';path=/';
    }
    setCookie('PirkumsVeikts', 'True');

setCookie(testCookie, 123);

然后我运行getCookie();

getCookie('testCookie')

它将打印“123”,但我需要它打印它而没有双引号,这可能吗?

3 个答案:

答案 0 :(得分:0)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

var cookie_value_as_int = parseInt(getCookie('testCookie'));

答案 1 :(得分:0)

您要返回的cookie只是一个字符串:

&#13;
&#13;
Enabled
&#13;
&#13;
&#13;

如果需要,您可以通过将其转换为Number()的数字,将其转换为数字:

function getCookie(cname) {
  var name = cname + '=';
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
}

function setCookie(cname, value) {
  document.cookie = cname + '=' + value + ';' + ';path=/';
}

setCookie('testCookie', 123);
console.log(getCookie('testCookie'));

或者将其解析为parseInt()

Number(getCookie('testCookie'));

希望这有帮助! :)

答案 2 :(得分:0)

只需使用parseInt将值返回转换为整数:

var number = parseInt(getCookie('testCookie'));