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

Home Posts Topics Members FAQ

Array and Hash in JavaScript : materials for FAQ : v2

VK
A while ago I proposed to update info in the group FAQ section, but I
dropped the discussion using the approach "No matter what color the cat
is as long as it still hounts the mice". Over the last month I had
enough of extra proof that the cat doesn't hount mice anymore in more
and more situations. And the surrent sicretisme among array and hash is
the base for it.

I summarized all points in this article:
<http://www.geocities.c om/schools_ring/ArrayAndHash.ht ml>

I invite all members of the previous discussion, as well as anyone
interested in Array vs Hash mechanics in JavaScript to read this
article and to express your opinion (if any).

As each point in the article is illustrated by a concrete code sample,
I expect do not see any abstract considerations/injurations. But of
course factual mistakes illustrated by contre-samples should be edited
immediately.

Jul 23 '05 #1
22 4666
"VK" <sc**********@y ahoo.com> writes:
I summarized all points in this article:
<http://www.geocities.c om/schools_ring/ArrayAndHash.ht ml>

I invite all members of the previous discussion, as well as anyone
interested in Array vs Hash mechanics in JavaScript to read this
article and to express your opinion (if any).


Comment: "You can use a notation like arrayObject[-1] top address the
last element in the array". Nope, doesn't work. It merely tries to
access the property named "-1", which doesn't exist unless you created
it.
Re. "multidimension al arrays". Javascript doesn't have mutidimensional
arrays in the sense of C, b ut only arrays of arrays. In C you wouldn't
be able to change a sub-array like:
int arr[4][4];
arr[3] = new int[4];

"The actual amount of possible indexes (dimensions) is platform
dependent, but always very big, so you should not worry about it."
It's not really platform dependent either, just limited by available
memory. Or, for a seemingly infinite-dimension array:
var x = []
x[0] = x;
You need to define what you mean by "element" of an array. You use it
in the sense "what you get when indexing with an integer less than the
array's length". That makes "new Array(10)" have ten elements, all
undefined. Other people (myself included) uses "element" to mean
an actual property of the array object, so "new Array(10)" has no
elements. This is a more usual meaning for *sparse* arrays, where
not all indices correspond to an "element".

You sortof say it in the section following this:
" Nevertheless it is important to understand the difference of (1)
undefined value received from a non-instantiated element within your
array and (2) undefined value received when addressing an element with
index bigger than length-1."

I think that's a dangerous way to make the point. There is no
difference between the "undefined" values you get, nor between the
underlying functionality that gives you that "undefined" . What you
are trying to say is that:
Arrays in Javascript are an abstraction on top of normal object
properties. For property names that are (bounded) integers, it
works as if the array was a contiguous sequence of values, some
of them "undefined" , indxed from 0 to one less than the arrays
"length" property's value.
Arrays are *implemented* as sparse arrays. Only the indices that have
been assigned to, take up space, and the "length" property only
guarantees to be larger than the largest index in use.
The methods operating on arrays respect the abstraction and all treat
the array as a contiguous sequence of, potentially "udefined" values.
[[ your example with "slice" ]].
Make no mistake, at the specification level, there is a difference
between being unassigned and having been assigned the value
"undefined" . Example:

var arr = [1,,undefined,tr ue];
arr[2]=undefined; // for IE's bug (2 in arr == false)
delete arr[1]; // for Firefox's bug (1 in arr == true)
alert([arr.length, 1 in arr, 2 in arr]); // 4,false,true
arr = arr.sort();
alert([arr.length, 2 in arr, 3 in arr]); // 4,true,false

I.e., unassigned indices are sorted as larger than those assigned
"undefined" . (Not all implementationt s are correct, e.g., Firefox
gives 4,true,true for the last one).
"On Macintosh platform an attempt to use a number for hash key leads
to an error. As a workaround, if you really need to have a number as
hash key (?), always put it into quotes."

Are you talking about Javascript objects here? It's not obvious.
Also, "Macintosh platform" is far from an exact specification of
the Javascript implementation that fails. It could be the one in
IE5.2, in Safari, in Galleon, in OmniWeb, ...

"JavaScript doesn't have a built-in constructor for hash objects. But
each object supports hash table mechanics inherited from the Object
prototype."
It's not Object.prototyp e that have string based properties, it's
just objects themselves. If you find a way to create an object without
inheriting Object.prototyp e, you can still add properties to it.

"Unfortunat ely interpreter doesn't resolve variables in such
declarations. Everything (quoted or not quoted) will be treated as
string literals."
Not so. It's variables in the keys that doesn't work, the values
work fine:
var x = 42;
var h = {foo: x, x:x, "y":x, "Lorem ipsum, lala": x, "":x};
There is no guarantee that implementations have efficient property
look-up. It seems like IE have linear time look-up of properties.
What is an "out of papers" language?
"Later it was called "JavaScript collection" and blessed to the
standard". You are referring to the DOM standard, before mentioning it
in the next paragraph. It is called an "HTMLCollection ". It has the
interface:
interface HTMLCollection {
readonly attribute unsigned long length;
Node item(in unsigned long index);
Node namedItem(in DOMString name);
};
In the ECMAScript binding, both can be called indirectly by using the
square bracket notation (which is equivalent with the dot-notation
when the property name is a valid identifier).
<URL:http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html>
"I strongly encourage you while working with forms and frames always
use index notation:
document.forms[0].elements[0];
window.frames[0]
That will make your code more stable and predictable."
I disagree. Using numeric indices is not stable against changes
to the page. If you insert a form before the one you refer to here,
you also need to change the index. Instead use:
document.forms['formId'].elements['elementName']
widow.frames['frameName']
It is safer. You do get collections when more than one element
have the same name, but that should not come as a surprise to you,
if you created the form. You can just traverse that collection then.
(and yes,
document.forms. formId.elements .elementName
is just as good when elementName is a valid identifier)
"then later we should address them respectively:
arrayObject[0];
hashObject{'key '};"
I fail to see why the format of a literal should define the format
of a lookup, but well, you are entitled to your opinion :)
Generally: The part about arrays is ok, with small nitpicks. The part
about hashes doesn't seem as coherent. It's a jubmle of independent
points, without a common goal. In other words: Find out what your
main point is, and build up to it.

/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 #2
VK
Lasse Reichstein Nielsen wrote:
Comment: "You can use a notation like arrayObject[-1] top address the
last element in the array". Nope, doesn't work. It merely tries to
access the property named "-1", which doesn't exist unless you created
it.
My bad! Did not check it for addressing option. Changed to:

Although in array methods you may refer the last array element using
-1, it's not a negative index, it's just a shortcut: for instance
arrayObject.sli ce(10,-1) simply means
arrayObject.sli ce(10,arrayObje ct.length-1)

Re. "multidimension al arrays". Javascript doesn't have mutidimensional
arrays in the sense of C, b ut only arrays of arrays. In C you wouldn't
be able to change a sub-array like:
int arr[4][4];
arr[3] = new int[4];

"The actual amount of possible indexes (dimensions) is platform
dependent, but always very big, so you should not worry about it."
It's not really platform dependent either, just limited by available
memory. Or, for a seemingly infinite-dimension array:
var x = []
x[0] = x;
Changed through to a neutral form.

You need to define what you mean by "element" of an array. You use it
in the sense "what you get when indexing with an integer less than the
array's length". That makes "new Array(10)" have ten elements, all
undefined. Other people (myself included) uses "element" to mean
an actual property of the array object, so "new Array(10)" has no
elements. This is a more usual meaning for *sparse* arrays, where
not all indices correspond to an "element".

You sortof say it in the section following this:
" Nevertheless it is important to understand the difference of (1)
undefined value received from a non-instantiated element within your
array and (2) undefined value received when addressing an element with
index bigger than length-1."

I think that's a dangerous way to make the point. There is no
difference between the "undefined" values you get, nor between the
underlying functionality that gives you that "undefined" . What you
are trying to say is that:
Arrays in Javascript are an abstraction on top of normal object
properties. For property names that are (bounded) integers, it
works as if the array was a contiguous sequence of values, some
of them "undefined" , indxed from 0 to one less than the arrays
"length" property's value.
Arrays are *implemented* as sparse arrays. Only the indices that have
been assigned to, take up space, and the "length" property only
guarantees to be larger than the largest index in use.
The methods operating on arrays respect the abstraction and all treat
the array as a contiguous sequence of, potentially "udefined" values.
[[ your example with "slice" ]].
Well, I'm affraid my vision is the only one that stops us from
declaring native array methods "broken".
My point always was that we need to see the difference between the
hardware reality and the human abstractions to describe it. Unless
you're working on ASSEMBLER, you're always dealing with something that
doesn't really exist. But at least you should call it the same words as
people around do. If slice() and splice() and so treat the array this
and not other way (and not in JavaScript only), so be it.

I just see another simplification of JavaScript, that forces us
sometimes to name and notate very different things in the same way. And
after that to have discussions "What kind of Joe is it really?"
JavaScript has only undefined and null. So by describing the situation
"within array" / "outside of array" we can only talk of "undefined kind
1" and "undefined kind 2", and it's really confusing (but still needs
to be understood).
If we move on on say VBasic.Net, we have the standard triad Nothing /
Empty / Null.
So:
1) something set *by myself* to be nothing is Null.
2) something appeared "against its will" in an enclosing structure (but
never directly set yet) is Empty.
3) something totally out of the scope of my program is Nothing.

So if
arrayObject=new Array(); arrayObject[100]=null;
then arrayObject[100] is Null, arrayObject[99] is Empty, and
arrayObject[1000] is Nothing. It gets much easier, is it? :-)

But I don't think we shall reach a compromise here...

"On Macintosh platform an attempt to use a number for hash key leads
to an error. As a workaround, if you really need to have a number as
hash key (?), always put it into quotes."

Are you talking about Javascript objects here? It's not obvious.
Also, "Macintosh platform" is far from an exact specification of
the Javascript implementation that fails. It could be the one in
IE5.2, in Safari, in Galleon, in OmniWeb, ...
I hever was a Macintosh user, sorry. I guess the current platform is
OX? I saw references of this error in the Internet, but it would be
really great to check it through.
If there are any Macintosh users around here, they could run this quick
test:
<script type="text/javascript">
var a = new Object();
var b = [];
a[1] = 'foo';
b[1] = 'bar';
</script>
to see if any errors.
"JavaScript doesn't have a built-in constructor for hash objects. But
each object supports hash table mechanics inherited from the Object
prototype."
It's not Object.prototyp e that have string based properties, it's
just objects themselves. If you find a way to create an object without
inheriting Object.prototyp e, you can still add properties to it.
Changed to:

But each object has native hash table mechanics to keep its
property:value pairs

"Unfortunat ely interpreter doesn't resolve variables in such
declarations. Everything (quoted or not quoted) will be treated as
string literals."
Not so. It's variables in the keys that doesn't work, the values
work fine:
var x = 42;
var h = {foo: x, x:x, "y":x, "Lorem ipsum, lala": x, "":x};
My bad! Changed to:

Unfortunately interpreter doesn't resolve variables used in keys.
Quoted or not quoted they will be treated as string literals.
Nevertheless you can instantiate hash with values taken from variables:

var hashObject = {'key1':myVar1, 'key2':myVar2};

There is no guarantee that implementations have efficient property
look-up. It seems like IE have linear time look-up of properties.
I don't think so, because object properties (if you list them unsorted)
corresponde to the model "memory baskets" strusture. Their interpreter
can have some bug in it though. Any reliable time mesurements around
here? (and please on real hash, not on a build-in object's properties).

What is an "out of papers" language?
"out of papers" - first think through, then do (like C)
"out of life" - first do, then look what happens (like LiveScript or
Perl).

Any better terms?

"Later it was called "JavaScript collection" and blessed to the
standard". You are referring to the DOM standard, before mentioning it
in the next paragraph. It is called an "HTMLCollection ".
Changed
It has the
interface:
interface HTMLCollection {
readonly attribute unsigned long length;
Node item(in unsigned long index);
Node namedItem(in DOMString name);
};
In the ECMAScript binding, both can be called indirectly by using the
square bracket notation (which is equivalent with the dot-notation
when the property name is a valid identifier).
<URL:http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html>
A quot from my article: "...(later) ... ECMA did a good cleanup job in
their specifications (especially the 3rd and the last one issued in
Dec.1999)";

"I strongly encourage you while working with forms and frames always
use index notation:
document.forms[0].elements[0];
window.frames[0]
That will make your code more stable and predictable."
I disagree. Using numeric indices is not stable against changes
to the page. If you insert a form before the one you refer to here,
you also need to change the index. Instead use:
document.forms['formId'].elements['elementName']
widow.frames['frameName']
It is safer. You do get collections when more than one element
have the same name, but that should not come as a surprise to you,
if you created the form. You can just traverse that collection then.
(and yes,
document.forms. formId.elements .elementName
is just as good when elementName is a valid identifier)
See the cases I linked to the article. The isssue is to be sure that
you always get something what you asked for, not a substitution, even
if it is also usable sometimes.
"then later we should address them respectively:
arrayObject[0];
hashObject{'key '};"
I fail to see why the format of a literal should define the format
of a lookup, but well, you are entitled to your opinion :)
For the same reason we're talking about "undefined kind 1" and
"undefined kind 2". Different notation eliminates the question of what
are we doing or trying to reach.

Generally: The part about arrays is ok, with small nitpicks. The part
about hashes doesn't seem as coherent. It's a jubmle of independent
points, without a common goal.


The super goal is to pull out array and hash as separate and very
different *programming entity* from your "Great Mother"-like
HTMLCollection that supposes to include all and explains everything.
Because it doesn't, at least not anymore.

The mini goal to address numerous issues that should be included into
FAQ's such as:

1) arrayObject = new Array(); arrayObject['foo'] = 'bar';
arrayObject.len gth == 0;

2)
<http://groups-beta.google.com/group/comp.lang.javas cript/browse_frm/thread/a618747cf483e3f 5/5649fc9f65f33c2 0#5649fc9f65f33 c20>

3)
<http://groups-beta.google.com/group/comp.lang.javas cript/browse_frm/thread/8005d8ef77288c3 9/186b0f8e0789798 7?q=group:comp. lang.javascript +author:VK&rnum =39&hl=en#186b0 f8e07897987>

Jul 23 '05 #3
"VK" <sc**********@y ahoo.com> writes:
Well, I'm affraid my vision is the only one that stops us from
declaring native array methods "broken".
My point always was that we need to see the difference between the
hardware reality and the human abstractions to describe it.
I can agree on that. It is more the words used to describe the
abstraction that is my problem.
I just see another simplification of JavaScript, that forces us
sometimes to name and notate very different things in the same way. And
after that to have discussions "What kind of Joe is it really?"
JavaScript has only undefined and null. So by describing the situation
"within array" / "outside of array" we can only talk of "undefined kind
1" and "undefined kind 2", and it's really confusing (but still needs
to be understood).
My problem is that you use the *values* to distinguish "inside" and
"outside" the array. The values are the same, and (at a lower level)
for the same reason.

What distinguishes being inside and outside the array, is the indices,
not the values.

So, in other words:

When using the notation arr[index] , where "arr" is an Array object,
one of the following two scenarios holds:

If your index is a non-negative integer less than the length of the
array (as given by the "length" property), then you are accessing
an array element. It will be undefined if no value have been stored
at that index.

If your index is either not a non-negative integer, or not less than
the arrays length, then you are not accessing an array element, but
merely a property of the object.

Not perfect, but moves the distinction from undefined 1 vs undefined 2
to the indices used to access them.
If we move on on say VBasic.Net, we have the standard triad Nothing /
Empty / Null.
I'm not sure what makes it so standard, since I have never heard about
it before (but then again, I never did VB).
So:
1) something set *by myself* to be nothing is Null.
2) something appeared "against its will" in an enclosing structure (but
never directly set yet) is Empty.
3) something totally out of the scope of my program is Nothing.
I prefer throwing exceptions when people go outside of the scope of
the program, and initializing everything, so I would probably only
see Null. (Does it show that I'm usually doing Java? :)
So if
arrayObject=new Array(); arrayObject[100]=null;
then arrayObject[100] is Null, arrayObject[99] is Empty, and
arrayObject[1000] is Nothing. It gets much easier, is it? :-)
It makes some kind of sense, but I would presonally prefer to remove
"null" from Javascript rather than have one more value that means
really means "no value".
I hever was a Macintosh user, sorry. I guess the current platform is
OX?
OS-X is not a Javascript platform, so it is probably Safari. It still
has a few quirks in its Javascript engine, but I bet they'll be sorted
out soon enough.
There is no guarantee that implementations have efficient property
look-up. It seems like IE have linear time look-up of properties.


I don't think so, because object properties (if you list them unsorted)
corresponde to the model "memory baskets" strusture.


If I create an object and add the properties "x0" .. "x99", and then
read them out using for(var k in arr) {...} then they come out in the
same order as they were added, no matter if I add them forwards or
backwards. That shows no "memory basket" behavior.

Also, try this code:
---
var N = 10000; // try varying N.
var arr = {};

for (var i = N-1; i >= 0; i--) {
arr["x"+i] = true;
}
var res = [];

var t0 = new Date();
for (var i = 0; i < N; i++) {
var t = arr["x"+i];
}
var t1 = new Date();
alert((t1-t0)/N); // note - divides by N!
---
If IE was using a hash structure, then the result should be approx.
the same no matter what N is (limited by the granularity of the timer).
Instead it seems that doubling N gives an increase of little less than
a doubling ... i.e., accessing properties is not constant time, more
like linear.

Their interpreter can have some bug in it though. Any reliable time
mesurements around here? (and please on real hash, not on a build-in
object's properties).
I hope that above qualifies :)
What is an "out of papers" language?
"out of papers" - first think through, then do (like C)
"out of life" - first do, then look what happens (like LiveScript or
Perl).

Any better terms?


"designed"? :)
I disagree. Using numeric indices is not stable against changes
to the page. If you insert a form before the one you refer to here,
you also need to change the index. Instead use:
document.forms['formId'].elements['elementName']
widow.frames['frameName']

.... See the cases I linked to the article. The isssue is to be sure that
you always get something what you asked for, not a substitution, even
if it is also usable sometimes.
You always get what you ask for. Computers are not that inventive.
The big question is whether you know what you ask for.

If you have more than one form control with the same control name,
then accessing by name is obviously not unambiguous. You then get
a collection of the matches. But you *should* know whether the name
is unique, and if you don't, it's better that the code fails as
soon as possible.

I still recommend accessing by name, not index. Indices are too
fragile when the page changes.
For the same reason we're talking about "undefined kind 1" and
"undefined kind 2". Different notation eliminates the question of what
are we doing or trying to reach.
It all comes back to arrays not *really* being part of the language.
There is just an *object* with array-like behavior (which pretty
much boils down to the magic "length" property ... ignore "length",
and there is no difference between Arrays and Objects)
The super goal is to pull out array and hash as separate and very
different *programming entity* from your "Great Mother"-like
HTMLCollection that supposes to include all and explains everything.
Because it doesn't, at least not anymore.
I would rather define Array and Associative Array ("hash" smells too
much like a specific implementation) separatly, then show how each
can be approximated by a construct in Javascript (Array and Object).

In both cases, it is not a clean implementation, the underlying
object shows through the cracks. An object is never completely
free of properties (inheriting some from Object.prototyp e), and
an array is really just an object with a magic "legth".
The mini goal to address numerous issues that should be included into
FAQ's such as:

1) arrayObject = new Array(); arrayObject['foo'] = 'bar';
arrayObject.len gth == 0;


I'm not sure it qualifies as a *F*AQ, but it's worth repeating: Don't
use arrays unless you mean it.

/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 #4
VK

Lasse Reichstein Nielsen wrote:
"VK" <sc**********@y ahoo.com> writes:
Well, I'm affraid my vision is the only one that stops us from
declaring native array methods "broken".
My point always was that we need to see the difference between the
hardware reality and the human abstractions to describe it.
I can agree on that. It is more the words used to describe the
abstraction that is my problem.
I just see another simplification of JavaScript, that forces us
sometimes to name and notate very different things in the same way. And
after that to have discussions "What kind of Joe is it really?"
JavaScript has only undefined and null. So by describing the situation
"within array" / "outside of array" we can only talk of "undefined kind
1" and "undefined kind 2", and it's really confusing (but still needs
to be understood).


My problem is that you use the *values* to distinguish "inside" and
"outside" the array. The values are the same, and (at a lower level)
for the same reason.

What distinguishes being inside and outside the array, is the indices,
not the values.

So, in other words:

When using the notation arr[index] , where "arr" is an Array object,
one of the following two scenarios holds:

If your index is a non-negative integer less than the length of the
array (as given by the "length" property), then you are accessing
an array element. It will be undefined if no value have been stored
at that index.

If your index is either not a non-negative integer, or not less than
the arrays length, then you are not accessing an array element, but
merely a property of the object.

Not perfect, but moves the distinction from undefined 1 vs undefined 2
to the indices used to access them.


I guess you're talking array elements too materialistical ly despite
your overall philosophical approach :-)

Array alement:
A single data item in an array, identified by the array name and one or
more subscripts.
<http://publib.boulder. ibm.com/infocenter/lnxpcomp/index.jsp?topic =/com.ibm.xlf91l. doc/xlflr/lr571.htm>

So saying "array element" doesn't imply at all "some value". Same way
saying "table cell" doesn't imply "some cell content" (it could be
shiny empty).
Array element simply is someting located withing the borders of array's
row (matrix, cube, n-linked hypercube). These borders are delimited by
each dimension length, and only within these borders array methods are
operating and having some sense.

Maybe indeed "undefined 1" and "undefined 2" are still too abstract.
I'll work on it :-) Concerning the addressing of array elements beyond
the array lenght, I don't see the reason to specify what exactly we've
addressing in this case. Not an array and not for array for sure. Outer
space, and that's it.

I can imagine a durty trick like:
arr = [1,2,3];
arr["10000"] = "Hi!";
alert(arr[10000]);
but it's a durty trick, and nothing more. It's being explaned enough in
the "Array as Hash" section.

If we move on on say VBasic.Net, we have the standard triad Nothing /
Empty / Null.


I'm not sure what makes it so standard, since I have never heard about
it before (but then again, I never did VB).
So:
1) something set *by myself* to be nothing is Null.
2) something appeared "against its will" in an enclosing structure (but
never directly set yet) is Empty.
3) something totally out of the scope of my program is Nothing.


I prefer throwing exceptions when people go outside of the scope of
the program, and initializing everything, so I would probably only
see Null. (Does it show that I'm usually doing Java? :)


OK, I should say "rather standard in Microsoft languages Nothing, Empty
and Null". I guess so far it's the closest encounter of the words
"standard" and "Microsoft" in this group (just 4 chars apart ) :-))

Also, try this code:
---
var N = 10000; // try varying N.
var arr = {};

for (var i = N-1; i >= 0; i--) {
arr["x"+i] = true;
}
var res = [];

var t0 = new Date();
for (var i = 0; i < N; i++) {
var t = arr["x"+i];
}
var t1 = new Date();
alert((t1-t0)/N); // note - divides by N!
---
If IE was using a hash structure, then the result should be approx.
the same no matter what N is (limited by the granularity of the timer).
Instead it seems that doubling N gives an increase of little less than
a doubling ... i.e., accessing properties is not constant time, more
like linear.
Actually hash LOOKUP operation and stricture are optimized for
*semi-predictable intensive* value reading. So it should act a bit like
processor cache (by replacing pairs from one backet to other depending
on demands). The test I think to write tomorrow (if it's still reining)
has to accomodate this specifics. On randomized but repetititive
lookups a real hash has to show improving response time from one cicle
to another.

I disagree. Using numeric indices is not stable against changes
to the page. If you insert a form before the one you refer to here,
you also need to change the index. Instead use:
document.forms['formId'].elements['elementName']
widow.frames['frameName']


So do I with you by now. More tests needed. Needed too collect all
promising cases from this group and check it on current brousers.
Everything about form, window and frame. Will take some time.

and an array is really just an object with a magic "legth".

So it's a String then? And frames too? and...

And Canvas, Container, jLabel and jButton are really the same things,
just called differently in different context? Idealisme subjectif,
Monsieur! ;-)

Jul 23 '05 #5
"VK" <sc**********@y ahoo.com> writes:
I guess you're talking array elements too materialistical ly despite
your overall philosophical approach :-)
I am trying not to, but I might not have expressed it clearly enough :)
Array alement:
A single data item in an array, identified by the array name and one or
more subscripts.
<http://publib.boulder. ibm.com/infocenter/lnxpcomp/index.jsp?topic =/com.ibm.xlf91l. doc/xlflr/lr571.htm>
That works for me.
So saying "array element" doesn't imply at all "some value".
Well "single data item" pretty much sounds like "some value" to me.
In a sparse array, some elements can be empty (and not hold a single
data item), which is exactly what Javascript arrays are.
Maybe indeed "undefined 1" and "undefined 2" are still too abstract.
I'd say too concrete. The value is "undefined" (different from the
value being undefined :), but that doesn't really matter. What matters
is that one corresponds to an array element (an empty one) and the
other doesn't. The actual value ("undefined" ) is incidental.
I'll work on it :-) Concerning the addressing of array elements beyond
the array lenght, I don't see the reason to specify what exactly we've
addressing in this case. Not an array and not for array for sure. Outer
space, and that's it.
The problem with Javascript is that there is no encapsulation. You
can't hide implementation details ...
I can imagine a durty trick like:
arr = [1,2,3];
arr["10000"] = "Hi!";
alert(arr[10000]);
but it's a durty trick, and nothing more. It's being explaned enough in
the "Array as Hash" section.
I don't see the dirt in that (except using a string representation of
the integer instead of a number), which should ofcourse be explained
to be equivalent.
Actually hash LOOKUP operation and stricture are optimized for
*semi-predictable intensive* value reading. So it should act a bit like
processor cache (by replacing pairs from one backet to other depending
on demands).
That would be an optimizing hash table, where the hashing function
changes. Some implementations (like Java's HashMap) only changes the
hashing function on additions (based on the number of elements, to
avoid too many elements in one basket). Reading doesn't change
hashing.
The test I think to write tomorrow (if it's still reining)
has to accomodate this specifics. On randomized but repetititive
lookups a real hash has to show improving response time from one cicle
to another.
That's one design. I wouldn't require that of a hash table.
and an array is really just an object with a magic "legth".

So it's a String then? And frames too? and...


Arrays are objects, and they make no attempt at hiding it. They
accept all the typical operations on objects, e.g.,
4 in arr
arr.hasOwnPrope rty(4)
for(key in arr) { ...
delete arr[4]
These are object operations, that double as array operations only
because arrays are objects. Also, all the operations in
Array.prototype will also work for non-Array objects, as long as
they have a property called "length" with a number in it. It's
deliberatly designed so that they can be reused for non-array
purposes.

And Canvas, Container, jLabel and jButton are really the same things,


Now you are comparing to a language with encapsulation. Sure, all
JLabel's are also Object's, but since a Java Object has only very
little functionality, there is no overlap between Object and JLabel
operations. In Javascript, there is overlap between Object and Array
functionality.

/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 #6
VK
I edited the text of the article
<http://www.geocities.c om/schools_ring/ArrayAndHash.ht ml> up to my
compromise abilities. I would like to add to the very bottom something
like:

"Many thanks to Lasse Reichstein Nielsen (one of comp.lang.javas cript
gurus) for his sriticism and technical expertise. Despite the above
article doesn't totally correspond to his personal opinion."
Please let me know if it's OK (or your version).

And please don't look at this as an a** licking. I'll get s*** out of
anyone now and later to find out the truth (even if it appears to be
*not my truth*). I just used to be clear in copyrights in any
publication.

P.S. I did not touch the Frames/Forms/Elements section, because many
cases (including even today's harvest) show that:
either I'm right and you wrong or I'm partially right and you're
partially wrong, and the big picture is not layed out yet. But it is
indeed strange that very different browsers demonstrate an instability
in the same circumstances. Usually it's either IE-bug, or FF-bug etc.
"Browser-bug" would be too much to handle.

P.P.S. I'm still getting the exact picture of how a real hash (map,
associative array) should behave, so I could put the right test on it.
Unfortunately (for hash) it's a magic weather outside so the only
basket I'm concerned right now is our pick-nick basket my wife is
preparing on the kitchen :-)

Jul 23 '05 #7
VK
We need to leave right now, but the last warming up class of wine just
shoot me:

array consists of "data holders", and length indicates the amount of
data holders in each dimensions. and array methods go through all
registered data holders ans count them in their operations. But data
holder may indeed hold some data or do not, it's not a requirement.

a real Rein Riesling is something you need to think properly about
arrays :-)

Jul 23 '05 #8
Lasse Reichstein Nielsen wrote:
"VK" <sc**********@y ahoo.com> writes:
If we move on on say VBasic.Net, we have the standard triad Nothing /
Empty / Null.


I'm not sure what makes it so standard, since I have never heard
about it before (but then again, I never did VB).


Be proud of it. VB is rather a disease than a programming language
which is why so many kiddies and so less professionals use it.
PointedEars
Jul 23 '05 #9
Thomas 'PointedEars' Lahn wrote:
VB is rather a disease than a programming language
which is why so many kiddies and so less professionals
use it.


Then I don't think you have much corporate experience. Actually VB is
pretty popular in software companies (at least in W Europe that is)

--
Bart

Jul 23 '05 #10

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

Similar topics

26
9640
by: JGH | last post by:
How can I check if a key is defined in an associative array? var users = new array(); users = "Joe Blow"; users = "John Doe"; users = "Jane Doe"; function isUser (userID) { if (?????)
47
5118
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.
21
21240
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...
7
39853
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);
8
74895
by: J. B. Moreno | last post by:
What's the best (i.e. fastest) way to find out if an array contains a given value? Other than looping, the only way I know to do it is to use an associative array/hash instead.... Is there a better/faster way? I.e if I have a list of names, what's the best way to find out if the aray contains "jane"? --
38
5260
by: VK | last post by:
Hello, In my object I have getDirectory() method which returns 2-dimentional array (or an imitation of 2-dimentional array using two JavaScript objects with auto-handled length property - please let's us do not go into an "each dot over i" clarification discussion now - however you want to call - you call it ;-) array contains records of all files in the current dir. array contains records of all subs in the current dir
21
3235
by: yeti349 | last post by:
Hi, I'm using the following code to retrieve data from an xml file and populate a javascript array. The data is then displayed in html table form. I would like to then be able to sort by each column. Once the array elements are split, what is the best way to sort them? Thank you. //populate data object with data from xml file. //Data is a comma delimited list of values var jsData = new Array(); jsData = {lib: "#field...
104
17031
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from that array Could you show me a little example how to do this? Thanks.
7
3803
by: Sam Kong | last post by:
Hello! My question would not be very practical but just out of curiosity. In JavaScript, Array is a subclass of Object. Well maybe not exactly... but sort of... For normal objects, you can access members by writing either of the two. obj.memberName
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
10914
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
7834
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5684
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...
0
5872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4495
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
2
4071
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.