Reputation: 3084
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>
Upvotes: 3
Views: 784
Reputation: 78741
You could get your expected output by saying:
this.state = [];
this.state[0] = { 'temp' : 25 };
this.state[1] = { 'thermState' : "Notte" };
jsFiddle Demo producing your desired output
Let me try to explain the unexpected behaviour.
In Javascript, everything is an object. When you write this.state = [];
your this.state
variable becomes an Array object which is empty. You can add elements to it by writing this.state[number] = x
or this.state.push(x)
.
Javascript has no associative arrays. When you write this.state["temp"]=25;
you are setting a property on your Array object. You are not putting anything to the array itself. Now this.state
will have a property that you can access by this.state.temp
or this.state['temp']
, but it will not appear in the array itself, because it was not added to that.
Upvotes: 1
Reputation: 4092
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.
Upvotes: 2
Reputation: 81700
You need to use push
, if you want state to be an array:
this.state.push({"temp":25, "thermState": "Notte"});
Upvotes: 0
Reputation: 148744
change to :
this.state = {}; ................
properties can be added to object not to arrays.
Upvotes: 6