473,839 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

<FAQENTRY> Array and hash (associative array)

VK
Or why I just did myArray['item01'] = "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.

Hash (Associative array) doesn't exists in JavaScript as a separate
programming entity. But each object inherits internal hash mechanics
from Object() constructor. In hash all keys are CDATA strings (even if
you provide a number for a key, internally it's sorted and treated as a
string).
Now some JavaScript specifics: as Array extends Object, it can be also
used as a hash. So you can do something like:

var arr = new Array();
// add to array, arr.length == 1
arr[0] = 10;

// add new property (key/value pair)
// arr.length is *not* affected !
arr['foo'] = 'JavaScript is funny sometimes';

Form values always returned to function as strings.
So in a situation like
arr[myForm.myField. value] = 4; // say myForm.myField. value == 17
JavaScript cannot determine what do you want from it: whether
you want to add new property called "17" or you want
to add an array element with index 17.

To work securely with *array* you should do something like:

var arr = new Array();
....
var i = Math.parseInteg er(myForm.myFie *ld.value, 10);
if (i) {arr[i] = quantity;}

This is with a value check.
To skip on value check you can do runtime typisation by prefixing value
with "+" (script will try to convert the following expression into a
number):

app[+myForm.myField .value] = quantity;

Then later:
for (i=0; i<arr.length; i++) {
// check arr[i]
}
If you want to use hash (say using item names as your keys), you better
use the generic Object() constructor to have you hash free from
inherited properties.

var hash = new Object();
hash[key] = someValue;

Then later:

for (key in hash) {
// check hash[key]

Jul 23 '05 #1
47 5117
VK wrote:
Or why I just did myArray['item01'] = "Computers" but
myArray.length is showing 0. What a hey?
You mean like:-

<URL: http://www.jibbering.com/faq/#FAQ4_39 >

- and asking yourself why you expect adding (or assigning a value to) a
named property of an object to have a side effect on another of its
properties.
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.
There is no trend, it has always been common for individuals to apply
inappropriate terminology to technical subjects that they don't fully
understand (even invent their own), and it is common for that action to
cause confusion/misunderstandin g in others.
If you are doing *array", then you have to use only integer
values for array index, as it was since ALGOL.
That would depend on how you defined "array index". In ECMAScript 'array
index' is only a relevant concept in the specification of Array (ECMA
262 3rd edition: section 15.4) and particularly the algorithms for the
Array's special internal [[Put]] method (ECMA 262 3rd edition: section
15.4.5.1).

An 'array index' is a _string_ (P), where - ToString(ToUint 32(P)) ===
P -. Thus a string representation of a positive 32 bit signed integer (0
through ((2 to the power of 32) - 1)).
Hash (Associative array) doesn't exists in JavaScript as a
separate programming entity. But each object inherits internal
hash mechanics from Object() constructor.
Javascript is not a class-based language so when inheritance is talked
about in this context it is usually inheritance through the prototype
chain that is being refereed to. Arrays have their own prototype object
but that object has a prototype of its own that is the Object.prototyp e
object. Thus Arrays inherit all prototyped properties of Object that are
not explicitly defined on the Array.prototype object. But the only
property that Arrays actually inherit from the Object.prototyp e is the -
valueOf - method, all others are masked by properties defined on
Array.prototype .

All objects, Arrays, Objects, Functions, Regular Expressions, etc, are
instances of the native ECMAScript object. Thus they all have the
characteristics of the native ECMAScritp object, but not as a result of
inheritance, they have the characteristics of that object because they
_are_ that object. One of the primary characteristics of a native
ECMAScript object is that named properties may be added to that object
and assigned values at run-time. This is where the 'hashtable' and
'associative array'-like features of javascript come from.

The significant difference between an instance of a native ECMAScript
object that is acting as an Array and one that is not is that the Array
object has had its default internal [[Put]] method replaced with a
special alternative that cares whether the property names used to write
to the properties of the object qualify as an 'array index', and
additionally acts upon the Array's - length - property, under some
circumstances, if they do.
In hash all keys are CDATA strings
CDATA is not a relevant concept in ECMAScript. String primitives are
sequences of 16 bit Unicode code points.
(even if you provide a number for a key, internally
it's sorted and treated as a string).
The algorithm for bracket notation property accessors always calls the
internal ToString function on the evaluated result of the expression
within the brackets. This is language related and happens regardless of
whether the object is an Array or not.
Now some JavaScript specifics: as Array extends Object,
it can be also used as a hash.
It can be used as a 'hash' because it _is_ a native ECMAScript object,
not because it 'extends' Object.
So you can do something like:

var arr = new Array();
// add to array, arr.length == 1
arr[0] = 10;

// add new property (key/value pair)
// arr.length is *not* affected !
arr['foo'] = 'JavaScript is funny sometimes';
Yes you can.
Form values always returned to function as strings.
Gibberish! The 'value' properties of the DOM representations of form
controls are usually of String type. Functions and return values do not
come into it.
So in a situation like
arr[myForm.myField. value] = 4; // say myForm.myField. value == 17
JavaScript cannot determine what do you want from it: whether
you want to add new property called "17" or you want
to add an array element with index 17.
Javascript knows exactly what to do with that assignment. It assigns a
value to the property of the object with the name "17", and if the
object is an Array the Array's special [[Put]] method also observes that
the property name qualifies as an 'array index' and checks to see if the
Array's length property is less than 18 and makes it 18 if it is.
To work securely with *array* you should do something like:
'Securely'? You are gibbering again.
var arr = new Array();
...
var i = Math.parseInteg er(myForm.myFie *ld.value, 10);
if (i) {arr[i] = quantity;}

This is with a value check.
To skip on value check you can do runtime typisation by
prefixing value with "+" (script will try to convert the
following expression into a number):

app[+myForm.myField .value] = quantity;
If you want to make sure that a property name used with an Array always
qualifies as an 'array index' then you would do:-

i = String( i >>> 0);

- as the internal algorithm for that operation is equivalent to -
ToString(ToUint 32(i)) -, though converting the value to a string
primitive would be a bit pointless as that conversions is implicit in
the bracket notation property accessor.

But forcing unknown values into values that qualify as an 'array index'
without prior consideration of the nature of those values would be
misguided. User input should probably be verified with a regular
expression prior to its use as an array index, and then no forcing
conversion would be required.

<snip> If you want to use hash (say using item names as your keys),
you better use the generic Object() constructor to have
you hash free from inherited properties.

var hash = new Object();
hash[key] = someValue;

Then later:

for (key in hash) {
// check hash[key]


Using an Object when you don't need the overheads or side effects of the
Array's special [[Put]] method makes sense. But if you want a real
enumerable hash then implementing your own is the best option as it
avoids the potential for enumerable prototype extensions becoming
visible in for-in loops and hash keys accidentally clashing with
specification defined properties of Object objects.

Richard.
Jul 23 '05 #2
VK
Dear Richard,

FAQ 4.39 does exactly what I am fighting against: it assures that array
and hash (associative array) are the nearly the same entities, so you
just need to pay some extra attention to the syntacs. What I want to
put in is the truth that these are two very different entities you have
to deal very differently.
Also pls do not look at this as an attack onto JavaScript. It was a
BASIC of Internet, so from the beginning it needed to express the most
complicated things in the most simple way. It is not its fault that
some of its advantages became limitations 10-15 years later.

Jul 23 '05 #3
In article <11************ *********@g44g2 000cwa.googlegr oups.com>, VK
<sc**********@y ahoo.com> writes
Or why I just did myArray['item01'] = "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.

<snip>

It's not new round here :-(

Why the word 'hash'. Surely you mean anything that lets you put in a
property name and get out the right property value. There are several
ways of making that happen. Is a hash table really likely ?

John
--
John Harris
Jul 23 '05 #4
Jc
Richard Cornford wrote:
VK wrote:
Or why I just did myArray['item01'] = "Computers" but
myArray.length is showing 0. What a hey?


You mean like:-

<URL: http://www.jibbering.com/faq/#FAQ4_39 >

- and asking yourself why you expect adding (or assigning a value to) a
named property of an object to have a side effect on another of its
properties.


That FAQ entry does not adequately cover the misconception of how
associative arrays don't exist in javascript, nor does it talk about
the differences between using square bracket notation on an array
object versus a non-array object.

I think a new FAQ entry that discusses this in the context of the Array
object and refers to FAQ 4.39 for more info would be helpful. There's a
lot of good content in this thread that could be extracted, it would be
nice to be able to easily refer to it.

<snip>
So in a situation like
arr[myForm.myField. value] = 4; // say myForm.myField. value == 17
JavaScript cannot determine what do you want from it: whether
you want to add new property called "17" or you want
to add an array element with index 17.


Javascript knows exactly what to do with that assignment. It assigns a
value to the property of the object with the name "17", and if the
object is an Array the Array's special [[Put]] method also observes that
the property name qualifies as an 'array index' and checks to see if the
Array's length property is less than 18 and makes it 18 if it is.


Yes, Javascript knows exactly what to do, but the intentions of the
developer who wrote the line of code are not clear - did he intend to
use the value as an index or a property name based on what the text of
the value is? I think that was the point.

Jul 23 '05 #5
JRS: In article <11************ *********@g44g2 000cwa.googlegr oups.com>,
dated Sat, 18 Jun 2005 07:58:48, seen in news:comp.lang. javascript, VK
<sc**********@y ahoo.com> posted :
Or why I just did myArray['item01'] = "Computers" but myArray.length is
showing 0. What a hey?


For an array A, A.length is given by the highest non-negative integer
index in use (add one); it is not a count of the number of elements.

That wording probably needs to be refined; but AIUI it expresses the
essence.

I'm tempted to suggest that your myArray should be a myObject.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #6
Dr John Stockton <jr*@merlyn.dem on.co.uk> writes:
For an array A, A.length is given by the highest non-negative integer
index in use (add one);
Pedantically: The length property is *at least* one more than the
highest integer index. It can be more. :)

var a = [];
a.length = 1000; // length 1000 and no elements at all
it is not a count of the number of elements.


Even more not so. :)

/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.'
Jul 23 '05 #7
VK
> Why the word 'hash'

To get out of the term "associativ e array" which:
1) confusing ("integer with a floating part" for float number - we
don't say it, do we?)
2) too long to type and to pronounce. It's asking to be abbreviated
back to "array" like "you know what kind of array I'm talking about".

Hash is used as a programming term and entity in Perl, so it's not my
invention.

Jul 23 '05 #8
VK
> For an array A, A.length is given by the highest non-negative integer
index in use (add one); it is not a count of the number of elements.


It is not theoretically correct. We're having again a simplification in
the JavaScript mechnics. The things you have to do explicitly in say
Java or C++, are being done here automatically on the background.

If I do something like:

var arr = new Array();
arr[1000] = 1;

I indeed *resize* the array to hold 1000 new elements. Its length now
is 1001, it contains 1000 elements where arr[0] to arr[999] eq
*undefined*, and arr[1000] eq 1

Yes, unternally JavaScript doesn't keep 999 undefined values. Only
arr[1000] value really exists, undefined will be generated
automatically then addressing an element. But this internal mechanics
is really not of interes of end-users. They see what they see: array
length is always 1 more than the highest index, array contans length-1
elements, there unassigned elements have undefined value:

var arr = new Array();
arr[3] = 1;
for (i=0; i<arr.length; i++) {
alert((arr[i]==undefined)? 'undefined' : arr[i]);
}

Jul 23 '05 #9
VK
> Its length now is 1001
It must be an influence of the Arabian nights stories and beer (the
latter is more probable) :-) :-(

After having polished my math and brains, my post should be:

---------------------------------------------------------------------
It is not theoretically correct. We're having again a simplification in

the JavaScript mechnics. The things you have to do explicitly in say
Java or C++, they are being done here automatically on the background.

If I do something like:

var arr = new Array();
arr[1000] = 1;

I indeed *resize* the array to hold 1000 new elements. Its length now
is 1000, it contains 1000 elements where arr[0] to arr[998] eq
*undefined*, and arr[999] eq 1
Yes, unternally JavaScript doesn't keep 999 undefined values. Only
arr[999] value really exists, undefined will be generated
automatically then addressing an element. But this internal mechanics
is really not of interest of the end-users. They see what they should
see: each array
contains arrayObject.len gth elements indexed from arrayObject[0]
to arrayObject[arrayObject.len gth-1], there all non-initiated elements
have undefined value:

var arr = new Array();
arr[3] = 1;
for (i=0; i<arr.length; i++) {
alert((arr[i]==undefined)? 'undefined' : arr[i]);
}

Jul 23 '05 #10

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

Similar topics

27
2558
by: VK | last post by:
<http://www.jibbering.com/faq/#FAQ3_2> The parts where update, replacement or add-on is needed are in <update> tag. 3.2 What online resources are available? Javascript FAQ sites, please check these first:- <http://developer.irt.org/script/script.htm>
19
3619
by: VK | last post by:
http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/ b495b4898808fde0> is more than one month old - this may pose problem for posting over some news servers. This is why I'm starting a new one] I'd still like to finish this rounding mess. As a startup lemma we can take that VK is the worst programmer of all times and places: let's move from here forward please. The usability of any program depends on exact behavior...
31
3559
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I modify the current browser window? ----------------------------------------------------------------------- In a default security environment you are very limited in how much you can modify the current browser window. You can use ` window.resizeTo ` or ` window.moveTo ` to resize or move a window respectively, but that is it. Normally you can...
0
9856
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
9698
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
10910
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...
0
10589
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10654
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
10297
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
9426
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
5683
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3136
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.