3

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>
1
  • 1
    You can't have associative arrays in Javascript. this.state["temp"]=25 should be this.state{ "temp" : 25 } Commented Jan 31, 2012 at 10:40

4 Answers 4

6

change to :

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

properties can be added to object not to arrays.

Sign up to request clarification or add additional context in comments.

Comments

2
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.

Comments

1

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.

Comments

0

You need to use push, if you want state to be an array:

this.state.push({"temp":25, "thermState": "Notte"});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.