Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 574
Carles Andres Avatar asked Aug 31 '26 08:08

Carles Andres


1 Answers

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.

like image 79
Carles Andres Avatar answered Sep 02 '26 14:09

Carles Andres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!