开发者

javascript JSON.parse result problem on empty array with localStorage

I initialized a localStorage variable with the following function:

    if (!localStorage开发者_运维技巧["store"]) {
       var aaa = new Array();
       localStorage["store"] = JSON.stringify(aaa);
    }   

It seems to work ok, but when I try use that array in order to add elements with the following code:

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

I get the following error:

Uncaught TypeError: Object [] has no method 'push'

I am using Google Chrome 10.0.648.151 on Ubuntu.

Does anyone know what I might be doing wrong?

Thanks.


I tried the following code and it worked as expected:

<!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> 

It seems it has something to do with Prototype library, which I am using. Have a look at this: JSON.stringify() array bizarreness with Prototype.js

I still haven't worked out a solution, but I believe I on the right path.


Essentially, a JSON object is not an array and the push method only works with arrays in javascript. Is there a reason why you're not using the object literal method to add the array data to your JSON object?

e.g.

statistics.variable = one_stat;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜