Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript stringify array does not return expected behavior

I'm getting a weird behavior out of javascript, anyone can help me?

When I click on the 'test' link I get an alert with this string: "[]"

I was expecting something like : "[{'temp':25},{'thermState':'Notte'}]"

What am I doing wrong?

<html>
<head>
    <script type="text/javascript" charset="utf-8" src="js/json2.js"></script>
    <script type="text/javascript" charset="utf-8">

    function test(){
        this.radioStates="";
        this.state = [];
        this.state["temp"]=25;
        this.state["thermState"]="Notte";
        alert(JSON.stringify(this.state));
    }

    </script>
</head>
<body>
<a href="#" onclick="test()">test</a>
</body>
</html>
like image 391
Maurizio Pozzobon Avatar asked Jun 19 '26 11:06

Maurizio Pozzobon


2 Answers

change to :

this.state = {}; ................

properties can be added to object not to arrays.

like image 162
Royi Namir Avatar answered Jun 21 '26 01:06

Royi Namir


this.state = {}; // Declare as object
this.state["temp"]=25;
this.state["thermState"]="Notte";
alert(JSON.stringify(this.state));

or

this.state = [];
this.state[this.state.length]= {temp: 25};
this.state[this.state.length]= { thermState: "Notte"};
alert(JSON.stringify(this.state));

The first works as an associative array / object, the second works as an array of objects.

like image 38
Slappy Avatar answered Jun 21 '26 00:06

Slappy



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!