繁体   English   中英

使用localStorage的空数组上的javascript JSON.parse结果问题

[英]javascript JSON.parse result problem on empty array with localStorage

我使用以下函数初始化了localStorage变量:

    if (!localStorage["store"]) {
       var aaa = new Array();
       localStorage["store"] = JSON.stringify(aaa);
    }   

看来还可以,但是当我尝试使用该数组以便通过以下代码添加元素时:

  var one_stat = new Array( s1, s2 , resultat );
  var statistics = JSON.parse(localStorage["store"]);
  statistics.push( one_stat );
  localStorage["store"] = JSON.stringify(statistics);

我收到以下错误:

未捕获的TypeError:对象[]没有方法“推”

我在Ubuntu上使用Google Chrome 10.0.648.151。

有人知道我可能做错了吗?

谢谢。

本质上,JSON对象不是数组,而push方法仅适用于javascript中的数组。 为什么没有使用对象文字方法将数组数据添加到JSON对象的原因?

例如

statistics.variable = one_stat;

我尝试了以下代码,它按预期工作:

<!DOCTYPE html>         
<html>                  
<head>
<title>Prova</title>    
</head>                 
<body>
<script type="text/javascript"> 
        if (!localStorage["stor"] ) {

                localStorage["stor"] = JSON.stringify([]);
        }               

        var aa = JSON.parse( localStorage["stor"] ) ;
        console.log( aa ) ;
        aa.push( [ 1 , 2, 2 ] ) ;
        localStorage["stor"] = JSON.stringify( aa ) ;
</script>
I am trying, man
</body>
</html> 

似乎与我使用的Prototype库有关。 看看这个: JSON.stringify()与Prototype.js的奇怪关系

我仍然没有找到解决方案,但是我相信我走对了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM