简体   繁体   中英

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.

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?

eg

statistics.variable = one_stat;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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