473,581 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Check if key is defined in associative array

JGH
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 ????

Jul 23 '05 #1
26 9594
On Wed, 17 Nov 2004 20:21:24 +0000 (UTC), JGH <jo******@nospa m.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.
Jul 23 '05 #2
Michael Winter wrote:
On Wed, 17 Nov 2004 20:21:24 +0000 (UTC), JGH <jo******@nospa m.tds.net>
wrote:
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
}


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?thre...gle.com&rnum=1

Alexis
Jul 23 '05 #3
On Thu, 18 Nov 2004 10:09:15 +0100, Alexis Nikichine
<al************ **@somedomain.f r> 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.
Jul 23 '05 #4
JGH
"Michael Winter" <M.******@bluey onder.co.invali d> 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?


Jul 23 '05 #5
On Thu, 18 Nov 2004 14:55:23 +0000 (UTC), JGH <jo******@nospa m.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.
Jul 23 '05 #6
"Michael Winter" <M.******@bluey onder.co.invali d> wrote in message news:<opshmn6wl zx13kvk@atlanti s
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?
Jul 23 '05 #7
lk******@geocit ies.com (lawrence) wrote:
"Michael Winter" <M.******@bluey onder.co.invali d> wrote in message news:<opshmn6wl zx13kvk@atlanti s
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?


No, the opposite. You can loop through items in an array the same as
properties of an object.

If you have an array
var a = ["Joe", "John", "Jane"]
you can loop through with the numeric array index
for (var i = 0; i < a.length; i++)
{
echo(a[i]
}
or the property name
for (var i in a)
{
echo(a[i]
}

Using the numeric index is faster because looping through each
property requires allocating memory and initializing strings (the
property names are strings).

However, if you have a very sparse array -- for example, an array with
a length of 1000 but only 5 items in it -- looping by property name is
faster because it iterates over only the 5 actual items whereas
looping numerically iterates over all 1000.
var users = {}; // Braces, not parentheses


That's interesting. What exactly is being said here?


It's an object with no properties (aside from the properties all
Objects have).
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?


It's an object. It's the short form of
var users = new Object();
users.joe = "Jow Blow";
users.john = "John Doe";
users["jane"] = "Jane Doe";

http://msdn.microsoft.com/library/en...conobjects.asp

Regards,
Steve
Jul 23 '05 #8
On 18 Nov 2004 13:16:07 -0800, lawrence <lk******@geoci ties.com> wrote:

Steve answered most of your questions, so I'll cover the one thing I
notice he didn't address in detail.
"Michael Winter" <M.******@bluey onder.co.invali d> wrote in message
news:<opshmn6wl zx13kvk@atlanti s


[snip]
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?


As Steve said, it creates an object. To be more specific, it's an object
literal, similar to the other literal types (number, array, regular
expression, and string) in that it assigns an initialised value to an
identifier. In this case, though, the initialisation is just a simple
object like an empty string or array.
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?


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

Hope that helps,
Mike
[1] Just to explain the series of commas (elisions), they define "empty"
elements. Each elision adds one to the length property of the array, but
it doesn't actually add an array element.

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #9
JGH
Steve van Dongen <st*****@hotmai l.com> wrote in
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?


It's an object. It's the short form of
var users = new Object();
users.joe = "Jow Blow";
users.john = "John Doe";
users["jane"] = "Jane Doe";

Probably what happens when you create what looks like a hash array in
javascript is that the interpreter passes that to the code to create an
object which in turn creates a hash array. Proof of at least the first
half of that is in the fact that a hash array has the standard
properties of an object.

So you can't actually create a hash array in javascript -- the
interpreter just won't let you. However, every object you create is
probably actually a hash array.

Hence the reason for much of the confusion, IMO. People see something
like this:

var users = {};

All that says is create an "object" which is a pointer to an array of
pointers to strings, integers, functions, other objects, etc.

It never occured to me before but that's one thing that's nice about
perl. That extra layer of abstraction isn't there. Objects are openly
hashrefs.
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2531
by: Stefan Richter | last post by:
Hi, I want to create an associative Array with a PHP variable (article ID) as Key and another associative array as it's value. How do I instanciate it, how can I fill it? I want something like this:
6
2007
by: mark4asp | last post by:
Suppose I have the following code. It functions to randomly select a city based upon the probabilities given by the key differences in the associative array. . Eg. because the key difference between London and the previous element is 25 (40-15), London has a 25% chance of being selected. When I call the function getAssocItem to do this I...
4
2671
by: Robert | last post by:
I am curious why some people feel that Javascript doesn't have associative arrays. I got these definitions of associative arrays via goggle: Arrays in which the indices may be numbers or strings, not just sequential integers in a fixed range. www.sunsite.ualberta.ca/Documentation/Gnu/gawk-3.1.0/html_chapter/gawk_20.html (n.) A...
47
5053
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they are not at all. If you are doing *array", then you have to use only integer values for array index, as it was since ALGOL.
5
37693
by: soup_or_power | last post by:
Hi I have an associative array like this: arr=30; arr=20;arr=40;arr=10; I want the sort function to sort keys in ascending order of the values on the right hand side with the following result: x4,x2,x1,x3 Can anyone please help me write the function? Thank you
21
21135
by: scandal | last post by:
I am a javascript newbie working on a script that checks whether a "path" from one element in an array to another is "blocked." Currently, the script pushes an already processed cell index (hence an integer) into an array. To prevent rechecking already processed cells, the script iterates through the (sorted) array to see whether that...
35
6615
by: VK | last post by:
Whatever you wanted to know about it but always were affraid to ask. <http://www.geocities.com/schools_ring/ArrayAndHash.html>
7
39833
by: Robert Mark Bram | last post by:
Hi All! How do you get the length of an associative array? var my_cars= new Array() my_cars="Mustang"; my_cars="Station Wagon"; my_cars="SUV"; alert(my_cars.length);
2
3406
by: ctj951 | last post by:
What I am trying to do is implement a associative array to lookup data based on a key in C. This might simple to do in C++ but I'm restricted to use C. The size of the data for the table isn't too large but too large to structure the code as a clean chain of if/else or similar logic. Also, the lookup key values can be large, unpredictable and...
0
7788
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8137
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7890
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6545
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5667
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3813
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1397
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1127
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.