Forum Moderators: open

Message Too Old, No Replies

Javascript equivalent for 'key'=>'value' in PHP

         

benj0323

6:23 am on Oct 11, 2004 (gmt 0)

10+ Year Member



In PHP we can make arrays as follows:

$variable = array('key1'=>'value1','key2'=>'value2');

is it possible to do this in javascript?

Thanks for your help.

Lance

10:05 am on Oct 11, 2004 (gmt 0)

10+ Year Member



Is this what you're looking for?

var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday");

Bernard Marx

3:16 pm on Oct 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



[pre]
var variable = 67;
var map =
{
key1 : 'string_val',
key2 : variable,
'key3': function(){alert('blah')},
'if the key is not a valid variable name, or is reserved, quote it': true
}

alert(map.key1);
alert(map['key2']);
map.key3();
if( map['if the key is not a valid variable name, or is reserved, quote it'])
alert('OK?');
[/pre]

Rambo Tribble

3:36 pm on Oct 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If I interpret you correctly, you simply want to produce an associative array, which this demonstrates:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<script type="text/javascript">
var as_arr=new Array();
as_arr["key1"]="value1";
as_arr["key2"]="value2";
alert("Key 1 value = "+as_arr['key1']+ "\nKey 2 value = "+as_arr['key2']);
</script>
</body>
</html>

Bernard Marx

4:55 pm on Oct 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Objects are associative arrays, Mr Tribble, as I'm sure...

That's why I always consider that using the basic, Object, very slightly better. The only thing that Array brings to the table concern numerical indexing, which isn't any use to us, and the extra methods may cause false positives in queries.

The literal form is easier, but it could be:

as_arr = new Object();
as_arr.key1 = "value1";
etc

Rambo Tribble

5:27 pm on Oct 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Objects, in JavaScript, are name/value pairs which can be addressed through associative array syntax. Objects, however, support additional properties, such as methods, which, strictly speaking, associative arrays do not. I believe you would more correct in stating that all arrays are objects, rather than the converse.

[edited by: Rambo_Tribble at 5:32 pm (utc) on Oct. 11, 2004]

benj0323

5:27 pm on Oct 11, 2004 (gmt 0)

10+ Year Member



Well the main reason I want to be able to do this is because I need to be able to do a foreach loop, like this:

This is in PHP, but lets say I have an array:

$array = array('dog'=>'puppy','cat'=>'kitten');

foreach($array as $key=>$val)
{

}

Then in the foreach loop it will go through every array element (dog & puppy, kat & kitten) and I can use the variables $key and $val. So the first time it went through the loop $key would = 'dog', the second time 'cat'. $val would = 'puppy' the first time, the second time 'kitten'.

I just need to be able to do something like this in javascript. Thanks for your help.

Rambo Tribble

5:38 pm on Oct 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The JavaScript equivalent is for/in, as the following demostrates with an array and an object:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
html,body{height:100%;}
</style>
<script type="text/javascript">
function propFest(){
var ar=["a","b","c"];
var ob={a:1,b:2,c:3}
var pr="";
for(var prop in ar){
pr+=prop;
}
pr+=" - ";
for(var prop in ob){
pr+=prop;
}
alert(pr);

}
</script>
</head>
<body onclick="propFest();">

</body>
</html>

Obviously, the value of prop can be used to address the value stored under its index, as in ob[prop].

Rambo Tribble

7:05 pm on Oct 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A minor clarification on my previous statement: Objects are collections of name/value pairs.

Additionally, here's a little better demonstration of for/in:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function propFest(){
var ar=["a","b","c"];
var ob={x:1,y:2,z:3}
var val="",pr="";
for(var prop in ar){
pr+=prop;
val+=ar[prop];
}
pr+=" \& ";
val+=" \& ";
for(var prop in ob){
pr+=prop;
val+=ob[prop];
}
alert("Array ar \& object ob keys = "+pr+"\nArray ar \& object ob values = "+val);

}
</script>
</head>
<body onload="propFest();">

</body>
</html>

Bernard Marx

9:36 pm on Oct 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I believe you would more correct in stating that all arrays are objects, rather than the converse.

Yes indeed. But I didn't say that. I said "objects are associative arrays" aka maps, hashes, or, as you said "collections of name value pairs". I'm not keen on the term "associative array" in Javascript. It suggests that they are a special kind of array, with perhaps a 'normal', numerical array as the base, when really it's the other way around.

None of this is particularly important, but since all other Javascript peeves, like misuse of eval are already being championed, I occasionally take up this one. I believe that the reason we see maps done with Array objects is purely because their common name contains the word "array", and no other reason. You could use a String object and get the same result.

The only place this can have an effect is, as has been going on in the thread, the map is enumerated with a

for..in
. Normally, this would be OK, but what's normal for some...

I like to add methods to object prototypes. I find it can smooth some things out. Default prototype properties do not appear on enumeration, but newly added ones do - all the way down the chain. If there were added methods on the Array.prototype then the enumerations above would report that too.

Swap the prototype assignments.


Object.prototype.ObjectProto = 1
//or// Array.prototype.ArrayProto = 1

obj = {a:1}
arr = new Array()
arr.a = 1

for(p in obj) alert('obj has '+p)
for(p in arr) alert('arr has '+p)

The only conclusion I can come to is that if I put methods onto the Array.prototype, the I can still use Objects to hold data. If I put them on the Object.prototype, then enumeration goes up the creek for both Array and Object objects. Usng Object is for maps is just a matter of keeping those options open that bit longer.

Rambo Tribble

10:21 pm on Oct 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



While it verges on a pedantic delineation within the context of JavaScript, an array in JavaScript is an object with certain limited specifications. Since objects in JS are highly mutable, it certainly is possible to extend their character through the prototype, whether for indexed arrays or associative arrays, but then they are new objects which extend the intrinsic properties of the native array objects. In its native state, the JavaScript array supports a limited number of specific methods.

The reason I resist your characterization of the object as an array is, while it may have some validity in the JavaScript context, in many other languages the data types are much more segregated. To start getting loose with one's terms in the JavaScript context invites, well, a frivolous and anarchistic dissolution into an objectionable disarray.

Bernard Marx

8:43 am on Oct 12, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



While it verges on a pedantic delineation within the context of JavaScript

That's my game, as usual.
a frivolous and anarchistic dissolution into an objectionable disarray

..and, as usual, your sense of humour is much appreciated.

I don't think we should worry about other languages here. I like emphasising the similarities in syntax between Java¦Javascript, but it's worth pushing the differences in structure too, especially in this context.

JS arrays can be sparse, and (although I can't think of any use in practice) could have common, unremoveable default members. Any Java bod would look at JS arrays and say "That's not an array. It's just a collection of name-value pairs with names that happen to be ordered integers".

We understand each other anyway. My real point (which I will not let lie) is that, when creating a [whatever we are calling it today], it's better to use an Object. My main premise is that this is what they are for, and I call upon The Creators of Javascript to testify:


{a:'apples',b:'bananas',c:'crumpets'} // disorder ¦ disarray
['apples','bananas','crumpets'] // order ¦ array

My main reason in practice is that it lessens the chance of enumeration being ducked up should another part of the script (from someone else perhaps) use prototype methods.

Rambo Tribble

12:58 pm on Oct 12, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Good point about the potential for hit-and-run prototypes.

Rambo Tribble

2:53 pm on Oct 12, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I guess I cling to anything that suggests consistency between languages and platforms, despite the occasional obvious fundamental disparity, because of the constant disruption and revision I have experienced in my 33 years of programming. Anyone remember dBase II? How about UCSD P-system? GW Basic? Fortran IV? Oh, for some thread of consistency.

Bernard Marx

7:42 am on Oct 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have nowhere near that level of experience. I only started this relatively recently. However, in a previous life, I taught myself a little Basic, and studied (again, a little) Fortran and Pascal at university.

Those languages aren't in the least object based (from what little I can remember), with the only composite data type of any kind being an array - A thing with ordered, numerical indices that start at 0, and continue with no 'holes'.

When I turned to Javascript, whether the fault of the books/tutorials I read, or my previous experiences, I learnt about Array before Object, which is strange considering both the prototype hierarchy, and the fact that the first Javascript had no native Array type at all. It took me a good while before I finally overcame my preconceptions, which I accuse some of the learning material of reinforcing. So many books concentrate on what one does with Javascript objects, rather than what they are, or could be considered to be.

At the moment, I'm getting some practical mileage out of considering Object objects as functions - not in a programming sense, but mathematically. If you consider

undefined
to be part of the codomain of these functions, then the domain is practically universal. Just a silly idea, but it helps.

Jedi Vampire Coffee

8:25 am on Oct 13, 2004 (gmt 0)

10+ Year Member



Is this a private party, or can anybody join in?

Bernard Marx

9:33 am on Oct 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I certainly don't think anyone would Object.

Rambo Tribble

3:38 pm on Oct 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, we could always use Array() of fresh insight.

Lance

4:03 pm on Oct 13, 2004 (gmt 0)

10+ Year Member



Name one good reason there is any Value to watching this Pair argue?

coopster

5:11 pm on Oct 13, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



To Learn.

But I wouldn't call it an argument, more like discussion. I thought it was an excellent discussion from two obviously well-rounded javascript developers. I learned something today. Thanks ;)

It's discussion like this that makes the forum what it is.

Rambo Tribble

5:42 pm on Oct 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Lance, don't be silly; everyone knows arguments[] function to set parameters.

Jedi Vampire Coffee

10:09 am on Oct 15, 2004 (gmt 0)

10+ Year Member



heh - arguments make programs worthwhile