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>
change to :
this.state = {}; ................
properties can be added to object not to arrays.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With