Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 698
quardas Avatar asked Feb 02 '11 15:02

quardas


Video Answer


2 Answers

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" });
like image 144
SLaks Avatar answered Oct 09 '22 03:10

SLaks


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

like image 10
Pointy Avatar answered Oct 09 '22 01:10

Pointy