Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Associative Arrays

Status
Not open for further replies.

DaZZleD

Programmer
Oct 21, 2003
886
US
hi... is there any way to create an associative array in javascript with inline declaration (for normal arrays you would use var myArr = new Array("a", "b", "c");) ?


thank you very much

--------------------------
"two wrongs don't make a right, but three lefts do" - the unknown sage
 
Hello DaZZleD,

Maybe you mean this kind of statements?
[tt]
var a={"a":1,"b":2,3:5);
alert(a["a"]+"\n"+a[3]);
[/tt]
regards - tsuji
 
that would be what i need... but it doesn't work...
it says: Expected ')'

thank you

--------------------------
"two wrongs don't make a right, but three lefts do" - the unknown sage
 
right...

and the problem is that
var a={"a":1,"b":2,3:5);
should be
var a={"a":1,"b":2,3:5};

thanks again!

--------------------------
"two wrongs don't make a right, but three lefts do" - the unknown sage
 
Be careful! Associative arrays are NOT the same as objects - which is what you have been given.

Depending on your code, you may well end up with things not working as expected if you are assuming that these are the same as arrays.

Take the following test harness, for example. Both the array ('array1') and the object ('array2') return different things when they themselves are alerted, they return different constructor functions, and the toString method doesn't work on the object at all... So you may find things breaking if you assume the two are identical.

Personally, I would not be trying to emulate one with the other - rather "waste" a few lines of code than have code potentially not work at all.

Code:
<html>
<head>
	<script type="text/javascript">

		var array1 = new Array();
		array1['a'] = 'The letter A';
		array1['z'] = 'The letter Z';

		var array2 = {'a':'The letter A', 'z':'The letter Z'};

		alert(array1);
		alert(array2);

		alert(array1.constructor);
		alert(array2.constructor);

		alert(array1).toString();
		alert(array2).toString();

	</script>
</head>
<body></body>
</html>

Hope this helps,
Dan
 

The last two alerts, of course, should read:

Code:
alert(array1.toString());
alert(array2.toString());

The JS error stops, but both still have a different outcome, however.

Dan
 
DaZZleD,

Absolutely, that was what I had in mind. I failed to coordinate my brain and my hands... not the only time though. Sorry!

- tsuji
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top