Web Design Web Design Forum
Registration is free! Here you can view your subscribed threads, work with private messages and edit your profile and preferences Calendar Find other members Frequently Asked Questions Search
Home Web Design

Convenient web based access to our favorite web design Usenet groups

web design reviews

This is Interesting: Free Magazines for Graphics designers and webmasters  





Pages (4): [1] 2 3 4 »   Last Thread  Next Thread
Author
Thread Post New Thread   

Check if key is defined in associative array
 

JGH




quote this post edit post

IP Loged report this post

Old Post  11-21-04 - 09:16 AM  
How can I check if a key is defined in an associative array?

var users = new array();
users["joe"] = "Joe Blow";
users["john"] = "John Doe";
users["jane"] = "Jane Doe";

function isUser (userID)
{
if (?????)
{ alert ("This is a valid ID"); }
else
}

But what goes in place of the  ????



Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

Michael Winter




quote this post edit post

IP Loged report this post

Old Post  11-21-04 - 09:16 AM  
On Wed, 17 Nov 2004 20:21:24 +0000 (UTC), JGH <johnheim@nospam.tds.net>
wrote:

> How can I check if a key is defined in an associative array?

Just to dispel any misconceptions, there's no such thing as an associative
array in ECMAScript/Javascript. What you are actually using is a feature
of objects - their ability to have properties added at run-time.

> var users = new array();
> users["joe"] = "Joe Blow";
> users["john"] = "John Doe";
> users["jane"] = "Jane Doe";

Using an actual array is a waste. You aren't using it to store values by
ordinal number, you're just using the fact that it's an object.

var users = new Object();

or

var users = {};   // Braces, not parentheses

If the list is static, you could write:

var users = {
joe : 'Jow Blow',
john : 'John Doe',
jane : 'Jane Doe'
};

If an id contains an illegal character, specify the property name as a
string:

'mike-winter' : 'Michael Winter'

> function isUser (userID)
> 	    	{
> 	    	if (?????)
> 	    		{ alert ("This is a valid ID"); }
> 	    	else
> 	    }
>
> But what goes in place of the  ????

If there is no property that goes by the name contained in userID,
attempting to access that property will yield undefined. You can check for
that by comparing the type:

if('undefined' != typeof user[userId]) {
// valid ID
}

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.


Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

Alexis Nikichine




quote this post edit post

IP Loged report this post

Old Post  11-21-04 - 09:16 AM  
Michael Winter wrote:
> On Wed, 17 Nov 2004 20:21:24 +0000 (UTC), JGH <johnheim@nospam.tds.net>
> wrote:
> 
>
>
> If there is no property that goes by the name contained in userID,
> attempting to access that property will yield undefined. You can check
> for  that by comparing the type:
>
>   if('undefined' != typeof user[userId]) {
>     // valid ID
>   }

Until the day you notice that isUser( "pop" ) alerts that "pop" is a
valid ID, you'll get on fine with this solution.

Why so ? Because pop, (or push, length, slice...) is a member of Array
objects, and you can accidentally fall on it (and its typeof string is
"function"). The two syntaxes, user.pop and user["pop"], have similar
effects.

I advise you to check type against the expected type of user[userId]:

if( 'string' == typeof user[userId] ) {
// valid ID
}

Using arrays as associative containers has pitfalls; you may wish to
read the misnamed thread "Arrays as hash tables"

http://groups.google.com/groups?thr...
gle.com&rnum=1

Alexis


Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

Michael Winter




quote this post edit post

IP Loged report this post

Old Post  11-21-04 - 09:16 AM  
On Thu, 18 Nov 2004 10:09:15 +0100, Alexis Nikichine
<alexis.nikichine@somedomain.fr> wrote:

[snip]

> I advise you to check type against the expected type of user[userId]:
>
> if( 'string' == typeof user[userId] ) {
>    // valid ID
> }

Yes, that is better. I forgot about the existing properties that an object
will have, such as toString and prototype.

> Using arrays as associative containers has pitfalls [...]

Indeed. Notice that the first thing that both Lasse and Douglas said was
don't use an array. Use a simple object instead.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.


Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

lawrence




quote this post edit post

IP Loged report this post

Old Post  11-21-04 - 09:17 AM  
"Michael Winter" <M.Winter@blueyonder.co.invalid> wrote in message 
>
> This is an object literal that contains a list of property names and
> values. The property name can be simple like an identifier; essentially
> letters, numbers, underscores (_), and Dollar symbols ($).
>
> The property name can also be a number or string literal. In the latter
> case, this allows for more complex names that can't be normally be
> specified. Note that although a number can be used to name a property, it
> doesn't make the object an array. For example:
>
>    // Object literal
>    var obj = {
>      5 : 'five'
>    };
>    obj[5]        // 'five'
>    obj.length    // undefined
>
>    // Array literal [1]
>    var obj = [
>      ,,,,, 'five'
>    ];
>    obj[5]        // 'five'
>    obj.length    // 6

So object doesn't have a length() method. And when you go obj[5] with
an object, its not an index between the brackets, its a property name?
So you can iterate through the properties of an object much as you
would through a hash table?

What are the differences, in Javascript, between an object and a hash
table that has pointers to properties and functions?


Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

Michael Winter




quote this post edit post

IP Loged report this post

Old Post  11-21-04 - 12:15 PM  
On 20 Nov 2004 22:19:05 -0800, lawrence <lkrubner@geocities.com> wrote:

The footnotes in this post go into more detail. I'd only read them if
you're comfortable with what you know about the subject. You might get
confused otherwise.

[snip]

> So object doesn't have a length() method.

You mean length property.  :P

Correct, an object doesn't have its own built-in length property.

> And when you go obj[5] with an object, its not an index between the
> brackets, its a property name?

Exactly.

Between the brackets you place an expression. It can be simple, like a
number or string, or something more complex like a function call or string
concatenation. This is how you can create property names at run-time.

The expression is evaluated and converted to a string[1], and the proper
ty
name is accessed.

The difference between arrays and other objects when assigning to a
property, is that it treats numbers as a special case[2]. Numeric indice
s
can update the length property of an array, but other names do not.

> So you can iterate through the properties of an object much as you would
> through a hash table?

For the most part, yes, with a for..in statement:

for(var propName in obj) {
/* propName is a string containing the property name.
* You can access the property value with obj[propName]
*/
}

The important part to note is that properties have attributes. You can't
actually modify these attributes, but they do exist.

There are four: ReadOnly, DontEnum, DontDelete, and Internal. The ability
to enumerate object properties with the code above is affected by the
second attribute, DontEnum. If it's present, you can access the property
directly, but the code above will skip it. Many built-in properties have
this attribute set. Properties you have *created* yourself will never have
this attribute set, so they can always be enumerated.

> What are the differences, in Javascript, between an object and a hash
> table that has pointers to properties and functions?

Depends on what particular implementation you're contemplating.

The biggest difference is that ECMAScript objects always contain certain
properties such as toString. You have to be careful not to confuse these
existing properties with actual keys.

If you're comparing to Java's Hashtable object, another big difference is
that it can use any object type (as long as it implements the hashCode and
equals methods) as a key, whereas property names are always strings in
ECMAScript.

Hope that helps,
Mike


[1] That part is important. Some hash tables allow you to use different
types as keys, which might lead you to believe that:

var obj = new Object();
var arr = new Array();

arr[obj] = ...;

allows you to assign values based on the actual object (I did once).
However, what happens is the object is converted to a string. As most
objects will simply return '[object Object]', or something similar, you
have to be careful here.

Also note that

arr[5] and arr['5']

are the same as the number will be converted to a string.


[2] It performs, what is effectively,

/* Convert name to string.
*
* e.g.  arr[10], arr[0xa] and arr['10']
*       all become '10'
*/

propertyName = String(propertyName);

/* If name, converted to a number then back to string,
* remains the same, treat as array index. If not, treat
* as property name.
*
* e.g. 1  arr[10], arr[0xa] and arr['10']
*         all become '10'. Converted to a number and back
*         to a string is still '10', and as '10' == '10',
*         they are all treated as array indices.
* e.g. 2  arr['0xa'] to a number and back to a string
*         is '10', but '0xa' != '10' so is a property, not
*         not an index.
*/

if(String(Number(propertyName)) == propertyName) {

/* If the array index is greater than, or equal to, the
* length of the array, update the length property.
*/

if(Number(propertyName) >= array.length) {
array.length = Number(propertyName) + 1;
}
}

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.


Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

JGH




quote this post edit post

IP Loged report this post

Old Post  11-22-04 - 05:18 PM  
"Michael Winter" <M.Winter@blueyonder.co.invalid> wrote in
> If an id contains an illegal character, specify the property name as a
> string
[...]
> Hope that helps,

It helped a lot. I got my old code (the stuff you corrected) off a
tutorial on the web.  So that's why I was unaware I was doing it wrong.

Anyway, it mostly works now. Problem is the values for user ids and
names come from a database and may contain  illegal values. I'm
generating the list of user ids and names via a few lines of visual
basic. But what it ends up with is something like this:


var users = {
~!# : 'Don't use this id',
'ton : 'O'Neal, Ted',
joe : 'Jow Blow',
john : 'John Doe',
jane : 'Jane Doe'
};

There are non-alpha characters in the ID and apostrophe's in the name.
That's why I was using quotes in my original code. Is that wrong?






Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

Michael Winter




quote this post edit post

IP Loged report this post

Old Post  11-22-04 - 05:19 PM  
On Thu, 18 Nov 2004 14:55:23 +0000 (UTC), JGH <johnheim@nospam.tds.net>
wrote:

[snip]

> There are non-alpha characters in the ID and apostrophe's in the name.
> That's why I was using quotes in my original code. Is that wrong?

Either single- or double-quotes are fine. I used single out of habit
rather than neccessity. Just make your VB code place double quotes around
all values so you end up with:

var users = {
"~!#" : "Don't use this id",
"'ton : "O'Neal, Ted",
"joe" : "Jow Blow",
"john" : "John Doe",
"jane" : "Jane Doe"
};

I assume that double quotes can't occur but if, for some reason, you do
need to include a double quote, output it as \":

"\"This value contains quotes\""

Good luck,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.


Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

Grant Wagner




quote this post edit post

IP Loged report this post

Old Post  11-22-04 - 05:20 PM  
JGH wrote:

> "Michael Winter" <M.Winter@blueyonder.co.invalid> wrote in 
> [...] 
>
> Anyway, it mostly works now. Problem is the values for user ids and
> names come from a database and may contain  illegal values. I'm
> generating the list of user ids and names via a few lines of visual
> basic. But what it ends up with is something like this:
>
> var users = {
>         ~!# : 'Don't use this id',
>         'ton : 'O'Neal, Ted',
>         joe : 'Jow Blow',
>         john : 'John Doe',
>         jane : 'Jane Doe'
>      };
>
> There are non-alpha characters in the ID and apostrophe's in the name.
> That's why I was using quotes in my original code. Is that wrong?

No, if you can't be guaranteed that the property is going to contain special
characters or not, it would be wise to always surround it in quotation
marks:

var users = {
'~!#' : 'Don't use this id',
''ton' : 'O'Neal, Ted',
'joe' : 'Jow Blow',
'john' : 'John Doe',
'jane' : 'Jane Doe'
};

In addition to escaping single quotation marks, you should consider that the
data from the database may contain new line characters and replace those
with \n or \r.

--
Grant Wagner <gwagner@agricoreunited.com>
comp.lang.javascript FAQ - http://jibbering.com/faq



Post Follow-Up to this message ]
Re: Check if key is defined in associative array
 

lawrence




quote this post edit post

IP Loged report this post

Old Post  11-23-04 - 04:22 AM  
"Michael Winter" <M.Winter@blueyonder.co.invalid> wrote in message news:<opshmn6wlzx13kvk@a
tlantis
> Using an actual array is a waste. You aren't using it to store values by
> ordinal number, you're just using the fact that it's an object.

You can loop through the properties of an object the same way you can
loop through an array?



>    var users = {};   // Braces, not parentheses

That's interesting. What exactly is being said here? Two braces
suggests, to me, a block of scope or a function. But a function would
usually have a name. Is this sort of like creating a fuction called
users and then, at the same time, creating a reference to it?




> If the list is static, you could write:
>
>    var users = {
>      joe : 'Jow Blow',
>      john : 'John Doe',
>      jane : 'Jane Doe'
>    };

This looks to be like an array. If it is not, then what is it?


Post Follow-Up to this message ]
Sponsored Links
 





All times are GMT. The time now is 01:07 PM. Post New Thread   
Pages (4): [1] 2 3 4 »   Previous Last Thread   Next Thread next
JavaScript archive | Show Printable Version | Email this Page | Subscribe to this Thread

Popular forums

Adobe Photoshop forum Macromedia Flash Web Site Design
Dreamweaver FrontPage forum
JavaScript Forum XML forum
Style Sheets VRML
Forum Jump:
Rate This Thread:

 

XML RSS Feed web design latest articles Syndicate our forum via XML or simple JavaScript

Web Design archive  Database administration help  


Top Home  -  Register  -  Control Panel   -  Memberlist  -  Calendar  -  Faq  -  Search Top