quardas
quardas

Reputation: 691

Is it possible to declare associative array in the function caller?

I want to declare associative array in the argument of function in - is it possible??

this code it's not working..

<a href="javascript:functionName(new Array('cool'=>'Mustang','family'=>'Station'))">click</a>

that code is working - is it the only way?

<script>
    var my_cars= new Array()
    my_cars["cool"]="Mustang";
    my_cars["family"]="Station";
</script>

<a href="javascript:functionName(my_cars)">click</a>

Upvotes: 6

Views: 18412

Answers (3)

Aravindan R
Aravindan R

Reputation: 3084

This will work.

<a href="javascript:functionName({'cool':'Mustang','family':'Station'})">click</a>

In JS Objects are associate arrays

Upvotes: 6

SLaks
SLaks

Reputation: 888185

You're trying to using PHP syntax in Javascript.

You need to use Javascript syntax to create an object literal:

functionName({ cool: "Mustang", family: "Station" });

Upvotes: 20

Pointy
Pointy

Reputation: 413996

Don't use "new Array()" when all you want is an object with strings as property names:

var my_cars = {};
my_cars["cool"]="Mustang";
my_cars["family"]="Station";

or just

var my_cars = {
  cool: 'Mustang', family: 'Station'
};

Arrays are intended to support integer-indexed properties, and they also maintain the "length" of the list of integer-indexed properties automatically (well, the "conceptual" length).

Upvotes: 10

Related Questions