Nitish
Nitish

Reputation: 2763

Creating an associative array using JavaScript

I am trying to create an associative array in JavaScript:

<script>
    var cst_dta = new Array('name' => 'amar', 'total_bill' => 'akbar', 'phone' => 'anthony');
    $(document).ready(function(){
        alert(cst_data);
    });
</script>

But the above code is not alerting anything! What's wrong with the array?

Upvotes: 0

Views: 134

Answers (2)

schnill
schnill

Reputation: 955

You can use objects as associative arrays:

var cst_dta = {name:'amar',total_bill:'akbar',phone:'anthony'};

And you can access it as,

cst_data['name'] or cst_data['phone'] or ..

But it doesn’t seem very useful in this case. Here cst_data.name is fine to use.

Basically, objects are used as associative arrays to bind arbitrary strings to arbitrary values, usually dynamically. Like for example, here you are getting a stock name value from the user at runtime:

var stock_name = get_stock_name_from_user();
var shares = get_number_of_shares();
portfolio[stock_name] = shares;

Since the user enters stock names at runtime, there is no way that you can know the property names ahead of time. Since you can't know the property names when you write the program, there is no way you can use the . operator to access the properties of the portfolio object.

You can use the [] operator, however, because it uses a string value (which is dynamic and can change at runtime) rather than an identifier (which is static and must be hardcoded in the program) to name the property.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

Didn't it occur to you that JavaScript isn't PHP?

This is simply not the correct syntax.

Use:

var cst_dta = {
      'name' : 'amar',
      'total_bill' : 'akbar',
      'phone' : 'anthony'
};

You have much more details on object literals (and other literals) on this page.

Upvotes: 4

Related Questions