小编Art*_*mis的帖子

使用 js-cookie 和 JSON.parse 从 cookie 设置和获取数组

我正在使用 js-cookie 来存储数据并取回数据,我试图破坏数组变量,但在维护其格式时遇到困难。这是创建、检索、更改和保存 cookie 数据的过程,它可以工作,但只是第一次,因为我无法

// store array in cookie  
Cookies.set('points', '0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0', { expires: 30 });

// get data from cookie into a variable (becomes a string)  
points = Cookies.get('points');

// convert to object with (length 12)
points = JSON.parse("[" + points + "]");

// change value of the array in the varable position
points[playerId]++;

// save data in cookie
Cookies.set('points', points, {expires: 30});
Run Code Online (Sandbox Code Playgroud)

这仅在第一次有效,任何后续时间我都会收到错误并且数组长度变为1。我确信这是因为我缺少方括号,但如果我尝试:

Cookies.set('points', '[0, 0, 0, …
Run Code Online (Sandbox Code Playgroud)

javascript cookies js-cookie

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

cookies ×1

javascript ×1

js-cookie ×1