473,714 Members | 2,552 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

length of an associative array

Hi All!

How do you get the length of an associative array?

var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(my_cars.l ength);

This reports 0. I know I can write a helper method, but I would rather not
iterate through an array to find its length:

function associativeArra yLength(array)
{
length = 0;
for (var object in array) {
length++;
}
return length;
}

Has anyone encountered this before?

Rob
:)
Aug 7 '05 #1
7 39846
Lee
Robert Mark Bram said:

Hi All!

How do you get the length of an associative array?

var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(my_cars. length);

This reports 0. I know I can write a helper method, but I would rather not
iterate through an array to find its length:

function associativeArra yLength(array)
{
length = 0;
for (var object in array) {
length++;
}
return length;
}

Has anyone encountered this before?


You're not really adding elements to an array.
Your adding new attributes to the Array object.
It would work just exactly the same as:

var my_cars = new Object();
my_cars["cool"]="Mustang";

Objects (Array or otherwise), have no attribute or method
that reflects the number of attributes they have.

Aug 7 '05 #2
VK
> You're not really adding elements to an array.
Your adding new attributes to the Array object.
It would work just exactly the same as:

var my_cars = new Object();
my_cars["cool"]="Mustang";

Objects (Array or otherwise), have no attribute or method
that reflects the number of attributes they have.


Before saying such nonsense you better learn what is the array, what is
the associative array and how is it reflected in the Object structure.

To OP:
read <http://www.geocities.c om/schools_ring/ArrayAndHash.ht ml>

Aug 7 '05 #3
"VK" <sc**********@y ahoo.com> writes:
You're not really adding elements to an array.
Your adding new attributes to the Array object.
It would work just exactly the same as:

var my_cars = new Object();
my_cars["cool"]="Mustang";

Objects (Array or otherwise), have no attribute or method
that reflects the number of attributes they have.


Before saying such nonsense you better learn what is the array, what is
the associative array and how is it reflected in the Object structure.


That "nonsense" is absolutely corrent, in all respects, so you might
want to reconsider your reply.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 7 '05 #4
VK said the following on 8/7/2005 5:01 AM:
You're not really adding elements to an array.
Your adding new attributes to the Array object.
It would work just exactly the same as:

var my_cars = new Object();
my_cars["cool"]="Mustang";

Objects (Array or otherwise), have no attribute or method
that reflects the number of attributes they have.

Before saying such nonsense you better learn what is the array, what is
the associative array and how is it reflected in the Object structure.


Sounds like it is *you* who needs to learn better.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Aug 7 '05 #5
VK

Lasse Reichstein Nielsen wrote:
"VK" <sc**********@y ahoo.com> writes:
You're not really adding elements to an array.
Your adding new attributes to the Array object.
It would work just exactly the same as:

var my_cars = new Object();
my_cars["cool"]="Mustang";

Objects (Array or otherwise), have no attribute or method
that reflects the number of attributes they have.


Before saying such nonsense you better learn what is the array, what is
the associative array and how is it reflected in the Object structure.


That "nonsense" is absolutely corrent, in all respects, so you might
want to reconsider your reply.


OK, reconsidered. Just was thinking of another attack on my beloved
length :-)

To OP:
you may use Dictionary object on IE:
<http://msdn.microsoft. com/library/default.asp?url =/library/en-us/script56/html/jsobjdictionary .asp>

And it's rather easy to cross-emulate it for wannabes.

Time for the cuctom made PGH (Pretty Good Hash) #2?

Aug 7 '05 #6
Robert Mark Bram wrote:
Hi All!

How do you get the length of an associative array?


Just a thought, but in addition to Lee's reply, you could prototype a size()
function, which returns the correct length of the array:

Array.prototype .size = function () {
var l = this.length ? --this.length : -1;
for (var k in this) {
l++;
}
return l;
}

var array = new Array();
array['foobar'] = 'bar';
alert(array.siz e()); // alerts 1
JW


Aug 7 '05 #7
Robert Mark Bram wrote:
How do you get the length of an associative array?
Javascript doesn't have 'associative arrays', it has objects to which
arbitrarily named properties can be added at runtime. This is true of
all objects in javascript including Object objects, Arrays and
functions. This behaviour is often called an 'associative array' or a
'hash table' but in reality it is neither, and the use of those terms to
label the behaviour allows individuals with experience of languages that
do have associative arrays and hash tables to have expectations of the
behaviour of javascript that differs from how it actually behaves.
var my_cars= new Array()
The differences between an object created with new Object() and one
created with new Array are:-

1. The internal [[Prototype]] properties refer to
Object.prototyp e and Array.prototype respectively.
2. The internal [[Put]] method of the native ECMAScript
object is replaced for the Array with an alternative
that tests its property name argument to see if it is
either "length" or an 'array index', and performs some
additional actions in the event that the property name
used is either. (The standard internal [[Get]] method
is unchanged.
3. A "length" property is added to the object.

In all other respects the objects are identical and exhibit the same
behaviour.
my_cars["cool"]="Mustang";
Javascript has no special array accessing syntax, in the way, for
example, Java does. It has two property accessor notations; dot notation
and bracket notation.

my_cars['cool'] //bracket notation

is identical in behaviour to:-

my_cars.cool //dot notation

- in that they both resolve - my_cars - into a reference to an object
and then attempt to read the value of a property with the name "cool"
from that object.

Dot notation has the limitations that the token following the dot must
be an identifier; conforming to a limited character pattern and fixed at
the point of writing the code. Bracket notation uses an expression
within the brackets, which may be any string literal, but might also be
resolved/evaluated at runtime. Thus the possible property names on
objects are not limited, but the property names used with dot notation
property accessors can o9nly be the sub-set of possible names that also
qualify as Identifiers.

'Array index' property names are string representations of non-negative
integers less than 2 to the power of 32, and these property names can
never conform with the rules that defined Identifiers, so they can only
be referenced using bracket notation property accessors. (Bracket
notation property accessors always type-convert the evaluated result of
the expression within the brackets to a string, so arrayRef[0] is
equivalent to arrayRef["0"], and property names are always strings).

The fact that using a numeric index with an Array can only be done with
a bracket notation property accessor may give the impression that there
is a special array accessing syntax in javascript, because of the
similarities in the resulting code with languages like Java, but that is
not actually the case.
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(my_cars.l ength);
In the event that a value was assigned to an Array object with an 'array
index' property name (a string representation of a non-negative integers
less than 2 to the power of 32) then the special internal [[Put]] method
of the Array would examine the Array's "length" property and if it was
smaller than or equal to the numeric equivalent of 'array index'
property name it would assign "length" a value that was one greater.

None of the property names used above qualify as an 'array index' so the
Array's special internal [[Put]] method does no more than assign the
value provided to a property of the object with the name specified, in
exactly the same way as it would for any other object.
This reports 0. I know I can write a helper method,
but I would rather not iterate through an array to
find its length:

<snip>

Your problem is conceptual. You are interacting with an Array as if it
was an object (which it is), and objects do not have an interest in the
number of named properties they posses at any time.

Richard.
Aug 7 '05 #8

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

Similar topics

6
2017
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 need to send in 2 arguments. Is there a quick way to get the maximum key value in the associative
5
1959
by: mark4asp | last post by:
Suppose I wanted to create an array that was associative in 2 dimensions. The rows are associated with numbers. The columns with words. For instance for 3 columns. This array will have 20 rows of three columns and the words that I want to associate with the columns are 'Small', 'Medium' and 'Large'. All the array elements are positive integers. What's the easiest way to do this? The first 3 columns are shown below for the array that...
4
2688
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 collection of data (an array) where individual items can be indexed (accessed) by a string, rather than by...
2
1632
by: bubbabubbs | last post by:
Platform: Win2K/SP4 I am trying to use an associative array in JScript, but I am seeing something weird. Example: ArrayTest(); /////////////////////////////////////////////////// function ArrayTest() {
14
6701
by: Yereth Jansen | last post by:
Hi all, I encountered a problem with looping through an associative array. All worked perfectly with the following code: for (var menuItem in this.menuItems) { doSomething(); } where this.menuItems is an associative array. The problem occurred when
47
5080
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
37708
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
21209
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 integer is an element of the array. After reading about javascript arrays a bit more, I thought...
35
6650
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>
0
8801
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8707
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9314
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9074
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9015
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7953
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5947
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2520
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2110
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.