By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,990 Members | 1,710 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,990 IT Pros & Developers. It's quick & easy.

<FAQENTRY> Array and hash (associative array)

P: n/a
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.parseInteger(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
Share this Question
Share on Google+
47 Replies


P: n/a
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/misunderstanding 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(ToUint32(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.prototype
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.prototype 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.parseInteger(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(ToUint32(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

P: n/a
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

P: n/a
In article <11*********************@g44g2000cwa.googlegroups. com>, VK
<sc**********@yahoo.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

P: n/a
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

P: n/a
JRS: In article <11*********************@g44g2000cwa.googlegroups. com>,
dated Sat, 18 Jun 2005 07:58:48, seen in news:comp.lang.javascript, VK
<sc**********@yahoo.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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #6

P: n/a
Dr John Stockton <jr*@merlyn.demon.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/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #7

P: n/a
VK
> Why the word 'hash'

To get out of the term "associative 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

P: n/a
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

P: n/a
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.length elements indexed from arrayObject[0]
to arrayObject[arrayObject.length-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

P: n/a
VK wrote:
Why the word 'hash'


To get out of the term "associative 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.


"Hash" would be as wrong a term to apply as "associative array". It does
have a use as a programming term and it means something specific. And
that specific something has nothing to do with any of the specified
behaviour of objects in javascript (even if the implementation _may_ be
using HashTables/Maps as the representation of those objects).

All native ECMAScript objects (Objects, Arrays, Functions, Regular
Expressions, prototypes, etc, etc) allow arbitrarily named properties to
be added to them at run-time. It doesn't need the application of a
borrowed term, that is just what any ECMAScript object _is_.

Richard.
Jul 23 '05 #11

P: n/a
VK wrote:
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:


Apparently sober your maths are worse.
---------------------------------------------------------------------
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,
1001
it contains 1000 elements
1001 (unless you mean it contains 1000 elements equal to undefined, from
index 0 to 999).
where arr[0] to arr[998] eq *undefined*,
arr[0] to arr[998]
and arr[999] eq 1
arr[1000] == 1, arr[999] is one of the elements that was never assigned
a value.
Yes, unternally JavaScript doesn't keep 999 undefined
values. Only arr[999] value really exists,
arr[1000]
undefined will be generated
automatically then addressing an element.
But this internal mechanics
is really not of interest of the end-users.

<snip>

What exactly is an "end-user" of javascript? Surly the only sense in
which people use javascript is as a programming language (as a
programming language is the only thing that javascript is). And
javascript programmers absolutely do, and should, need to understand the
technical details of the behaviour of the language that they are using.

Without that understanding they will just find themselves wasting their
time thrashing about in the dark, attributing phenomena they observe but
don't understand to 'browser bugs' and other mystical explanations, and
achieving little of use or value to others.

Richard.
Jul 23 '05 #12

P: n/a
"VK" <sc**********@yahoo.com> writes:
Its length now is 1001
.... 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
Actually, the length property does have the value 1001, and it's
arr[1000] that equals 1.

Also, It's, pedantically, incorrect to say that the array holds 1000
(or 1001) elements. It holds exactly one enumerable property (1000), as
can be seen from:

var cnt = 0;
for (var i in arr) {
cnt ++;
}
alert(cnt); // alerts "1".

Try this to see the difference:

var arr = [];
arr[1000] = 1;
arr[500] = undefined;
// above loop gives 2, not 1
alert("500" in arr); // true
alert("501" in arr); // false
Yes, unternally JavaScript doesn't keep 999 undefined values. Only
arr[999] value really exists, undefined will be generated
automatically then addressing an element.
No, there is a difference between a property that exists and have
the value "undefined" and a property that doesn't exist. Reading
the latter will evaluate to "undefined" as well, but that's because
the language semantics says so (in particular the [[Get]] method
of objects).

There is *no* difference between arr[501] and arr[1500]. They are both
non-existing properties of the array object. The only thing that makes
you think otherwise is that one of them happens to be less than the
length property, and the other greater than.
But this internal mechanics is really not of interest of the
end-users. They see what they should see: each array contains
arrayObject.length elements indexed from arrayObject[0] to
arrayObject[arrayObject.length-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]);


Use "===" when comparing to undefined, or you will be surprised :)
Add arr[6] = null; to see.

Now try
for(i in arr) { // ...
or
alert((i in arr)?...)
and see the difference between initialized and not. Add some
arr[x]=undefined for fun.

Btw, an array literal can also leave places uninitialized:
var arr = [,,,1,,,2,,,];
should have
arr.length == 9 // but IE sucks and says 10.
and only
3 in arr && 6 in arr
be true. The remaining are undefined.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #13

P: n/a
VK
> What exactly is an "end-user" of javascript?

Nothing like "amateur" or "beginner", I did not mean *that*. End-user
is a person who's using JavaScript for programming, but who doesn't
program JavaScript engine itself (Using C++/C#). So for him it's
important to know the difference in all contexts between say:
var myVar = 0;
and
myVar = 0
At the same time it's irrelevant to him/her at what phisical address
this var will be allocated and how the system will manage to reallocate
the memory if latter (s)he will do
myVar = "Now it will be a string";
But (s)he must know that it's possible and that it will override the
previous value.

So it's equal for him/her if that "undefined" is just created by
internal sub or indeed was kept somewhere in the memory.

P.S. I'm fixing a VBA (not mine!) with OPTIONBASE changed to 1 for all
arrays. This is the reason of my temp math disability. In my 2nd
attempt please read
arr[999] = 1;
The rest is right then.

Jul 23 '05 #14

P: n/a
On 19/06/2005 13:29, VK wrote:
What exactly is an "end-user" of javascript?


[...] End-user is a person who's using JavaScript for programming, [...]


Then an end-user, in those terms, should understand how array operations
work, and shouldn't deceive themselves into thinking about array
resizing in memory.

As dynamic resizing is a feature that is often used, I doubt the
performance increase available from using static arrays when finding
values is worth the penalty of reallocation and wasted memory.

[snip]

I think it was agreed during the last round of discussion on
'associative arrays', that the use of such terms is fine if it aids
understanding, but it must not result in disguising what really occurs.
That is, it might help to think of certain aspects of native objects as
exhibiting the behaviour of associative arrays, but the individual must
understand that native objects are /not/ these constructs. The same
should apply to other features of ECMAScript.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #15

P: n/a
VK wrote:
What exactly is an "end-user" of javascript?
Nothing like "amateur" or "beginner", I did not mean *that*.
End-user is a person who's using JavaScript for programming,
but who doesn't program JavaScript engine itself
(Using C++/C#). So for him it's important to know the
difference in all contexts between say:
var myVar = 0;
and
myVar = 0
At the same time it's irrelevant to him/her at what
phisical address this var will be allocated and how
the system will manage to reallocate the memory if
latter (s)he will do
myVar = "Now it will be a string";
But (s)he must know that it's possible and that it
will override the previous value.


Not that it is possible that it will overwrite the previous value, but
that it _will_ overwrite the previous value. This is computer
programming; pure mechanical logic with absolutely deterministic
behaviour.

Yes the programmer of javascript does not need to know anything about
the language implementation. They do need to know about the language's
specified behaviour, in as much technical detail as possible. They need
that understanding to use the language well, and they need that
understanding in order to talk about the language to others in common
trems.
So it's equal for him/her if that "undefined" is just
created by internal sub or indeed was kept somewhere
in the memory.


That is exactly the sort of thing that a javascript programmer does need
to comprehend. There is an important difference between a property that
has been created but holds the Undefined value and a property that never
has existed. The distinction is critical to understanding scope chain
Identifier resolution and the prototype chian.

Richard.
Jul 23 '05 #16

P: n/a
VK
We're talking around Dr John Stockton's definition that joins in one
sentence two totally different context: low-level memory management and
high-level programming entity behavior. (This is why I did not accept
it).

No, the engine doesn't fill non-initialized array members with some
placeholders. That would be a waste of memory. (Low
level)
Yes, *programmically* each array consists of (array.length) members,
where non-initialized members have undefined value. (High level)

So *programmically* my proof is here:

var arrayObject = new Array(10);
arrayObject[100] = 1;
for (i=0; i<arrayObject.length; i++) {
// 100 cicles, 100 values
}

And *programmically* the properties collection
check below doesn't proof anything, because we're
downcasting Array back to Object and studying it
from that level. So we actually do (in Java notation):
(Object)arrayObject

for (objectProperty in arrayObject) {
// 1 cicle, 1 value for (Object)arrayObject
}

JavaScript frees programmer from the "manual" memory allocation, so
*any* array can have as many members as it allowed by the language
specs. So if we want to stay on the same low-level (where array
consists only from defined members), then

var arrayObject = new Array();
really means:
var arrayObject = new Array(1073741822); // for Windows platforms

and

var arrayObject = new Array(10);
really means:
// var arrayObject = new Array(10); // silently ignored
var arrayObject = new Array(1073741822); // for Windows platforms

But do we really want to stay so low? I would propose to move on the
normal programming level, where array has (array.length) members, and
declaration Array(10) indeed means something, and one should use push()
method to nicely add new members to an array.
P.S. So much for hash :-)

Jul 23 '05 #17

P: n/a
"VK" <sc**********@yahoo.com> writes:
We're talking around Dr John Stockton's definition that joins in one
sentence two totally different context: low-level memory management and
high-level programming entity behavior. (This is why I did not accept
it).
Difinition of what? Please include at least some context of what your
are replying to.
So *programmically* my proof is here:

var arrayObject = new Array(10);
arrayObject[100] = 1;
for (i=0; i<arrayObject.length; i++) {
// 100 cicles, 100 values
}

Proof of what. How does this differ from:

var arrayObject = new Array(10); //arrayObject.length == 10
for (i=0; i < 101; i++) {
// ... ?
}
And *programmically* the properties collection
check below doesn't proof anything, because we're
downcasting Array back to Object and studying it
from that level. So we actually do (in Java notation):
(Object)arrayObject
While I think I understand your point, comparing Javascript
to a class based language is rarely productive.

JavaScript frees programmer from the "manual" memory allocation, so
*any* array can have as many members as it allowed by the language
specs. So if we want to stay on the same low-level (where array
consists only from defined members), then

var arrayObject = new Array();
really means:
var arrayObject = new Array(1073741822); // for Windows platforms
No. The latter has arrayObject.length == 1073741822, not 0.
(And the length is an unsigned 32 bit number, so the highest index
in is
var ar = new Array();
ar[4294967294] = 1;
alert(ar.length); // 4294967295
)
var arrayObject = new Array(10);
really means:
// var arrayObject = new Array(10); // silently ignored
var arrayObject = new Array(1073741822); // for Windows platforms
You are trying to use Java arrays to understand and/or explain
Javascript arrays. However, the main difference is that in Java,
arrays have a fixed length, while in Javascript, they are dynamic.

But do we really want to stay so low? I would propose to move on the
normal programming level, where array has (array.length) members, and
declaration Array(10) indeed means something, and one should use push()
method to nicely add new members to an array.


You can do that, and most of the time it will work fine for
you. However, there will be the odd case where understanding how
arrays work, in particular that the length property only guarantees
to be at least one larger than the highest array index in use, is
necessary.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #18

P: n/a
VK wrote:
We're talking around Dr John Stockton's definition that
joins in one sentence two totally different context:
low-level memory management and high-level programming
entity behavior. (This is why I did not accept it).

No, the engine doesn't fill non-initialized array members
with some placeholders. That would be a waste of memory.
(Low level)
Yes, *programmically* each array consists of (array.length)
members, where non-initialized members have undefined
value. (High level)
But Arrays do not have - array.length - members at the high level, they
have a - length - property that describes the upper limit of their
members with 'array index' names. Useful if you want to perform a loop
that will catch all of the members with 'array index' names.
So *programmically* my proof is here:

var arrayObject = new Array(10);
arrayObject[100] = 1;
for (i=0; i<arrayObject.length; i++) {
// 100 cicles, 100 values
101 cicles, 101 values. Give up the drink.
}
Proof of what? We know that the loop will catch all of the array members
with 'array index' names, and we know that non-existent property names
will result in the Array's [[Get]] method returning the Undefined value
when used in a property accessor. So we expect 101 values only one of
which is not the Undefined value, because the array only has one member
that has an 'array index' name.
And *programmically* the properties collection
check below doesn't proof anything, because we're
downcasting Array back to Object
Will you stop applying this class-based terminology to javascript. There
is no casting here. The Array is, was, and always will be, an instance
of the native ECMAScript object.
and studying it from that level.
So we actually do (in Java notation):
(Object)arrayObject
You cannot cast objects in javascript because they are
all_of_exactly_the_same_type.
for (objectProperty in arrayObject) {
// 1 cicle, 1 value for (Object)arrayObject
}

JavaScript frees programmer from the "manual" memory
allocation, so *any* array can have as many members
as it allowed by the language specs.
The specification does not impose any limits on the number of members a
native ECMAScript object may have. An Array may not nave more 'array
index' named members than can be accommodated by the definition of
'array index', but it can have as many members with non-'array index'
names as the implementation and available memory will put up with.
So if we want to stay on the same low-level (where array
consists only from defined members), then

var arrayObject = new Array();
really means:
var arrayObject = new Array(1073741822); // for Windows platforms

and

var arrayObject = new Array(10);
really means:
// var arrayObject = new Array(10); // silently ignored
var arrayObject = new Array(1073741822); // for Windows platforms
How is it that you feel it appropriate to conjure this nonsense up from
your immagenation and write it down as if it means something?
But do we really want to stay so low? I would propose to
move on the normal programming level, where array has
(array.length) members, and declaration Array(10) indeed
means something, and one should use push() method to nicely
add new members to an array.
The "normal programming level" is to attempt to understand the language
being used, not make up stories about it off the top of your head.
P.S. So much for hash :-)


"What! drugs? I always thought your articles were a little too
inspired." (from: 'Sir Henry at Ndidi's Krall' by Vivian Stanshall
1984)

Richard.
Jul 23 '05 #19

P: n/a
VK
OK
JavaScript array is not really an array.
arrayObject.length keeps the highest index you managed to use so far.
It has *no* connection with the actual array's length, it's just called
so for further convenience.
Array contains as many elements as you initialized *yourselve*. If you
vant to know the real array length, you have to treat array as hash
table (map, collection) and iterate through its key/value pairs.
As the latter is the only way to treat JavaScript's array properly, it
doesn't really matter what your're doing: adding key/value pair to the
hash or adding indexed alement to the array. You're dealing with the
same object anyway.
push(), pop(), and other array methods are not needed in JavaScript.

I agree on everything stated above. Just one humble ask: please do not
put *this* to FAQ's.
Eppur si mouve!

Could we at least to mention in the FAQ's, that despite array and
associative array (map, collection, hash table) is the same thing in
JavaScript, its engine has some strange behavior:

if you do arrayObject[SomeNumber] = someValue, it counts it in
arrayObject.length
It also lets you to use standard array methods on this member. (1st
category)

if you do arrayObject[SomeString] = someValue, the engine doesn't it in
arrayObject.length
and you cannot use standard array methods on this member. (2nd
category)

Until JavaScript/JScript engine producer will rectify this obvious bug,
you need to be very attentive while putting new members in your
arrayObject.
As soon as array index is not an integer, new members falls into the
2nd category with all above listed consequences.

Jul 23 '05 #20

P: n/a
On 19/06/2005 20:40, VK wrote:
OK
JavaScript array is not really an array.
That probably depends on the definition that you want to use. The
definition that I'm accustomed to is a homogeneous collection of
elements located sequentially in memory. However, more generic
definitions are just as acceptable.

What arrays in ECMAScript certainly are, are Object objects with
specialised behaviour. The same can be said for any native object.
arrayObject.length keeps the highest index you managed to use so far.
The highest plus one.
It has *no* connection with the actual array's length, it's just called
so for further convenience.
I disagree. The array:

[, 1]

has two elements, and a length of two. Just because the first element is
undefined doesn't make the size any smaller. If you think it should,
then you are probably using the wrong data type.

[snip]
Could we at least to mention in the FAQ's, that despite array and
associative array (map, collection, hash table) is the same thing in
JavaScript
OK, how many times does this need to be said: an array is not an
associative array, and an object is not an associative array. That might
be how they are implemented, and that's the sort of behaviour they
appear to possess, but that doesn't change the reality of the situation.
if you do arrayObject[SomeNumber] = someValue, it counts it in
arrayObject.length
If SomeNumber is a 32-bit unsigned integer, yes.
It also lets you to use standard array methods on this member. (1st
category)
The Array prototype methods generally operate in the range of named
properties [0, length), so that much is obvious. Some work outside that
range, namely when extending the number of elements.
if you do arrayObject[SomeString] = someValue, the engine doesn't it in
arrayObject.length
If SomeString represents an array index, then that assignment certainly
does affect the length. If SomeString is not an array index, then of
course it won't affect the length.
and you cannot use standard array methods on this member. (2nd
category)
For the previously cited reason.
Until JavaScript/JScript engine producer will rectify this obvious bug,
It is not a bug. It is clearly defined behaviour.
you need to be very attentive while putting new members in your
arrayObject. [...]


One merely needs to understand the language. You clearly don't. I
suggest you get yourself a copy of ECMA-262 and read items 15.4 and
15.4.5.1, and compare the latter to 8.6.2.2.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #21

P: n/a
Michael Winter <m.******@blueyonder.co.invalid> writes:
I disagree. The array:

[, 1]

has two elements, and a length of two.
I can see why Mr. VK gets confuzed, because I would say that this
array has one element and a length of two. It matters (to me) that
the array doesn't have a property called "0".

But then again, as Mr. VK also said, if I understood the Java
comparison correctly, arrays in Javascript is an abstraction on top of
an object. If you keep within the abstraction, you can treat the array
as having two elements. If you break the abstraction and uses the
array as a general object, then you need to know the implementation.

Safer languages protects their abstractions, Javascript is not one :)
OK, how many times does this need to be said: an array is not an
associative array, and an object is not an associative array. That
might be how they are implemented, and that's the sort of behaviour
they appear to possess, but that doesn't change the reality of the
situation.


<devil's advocate>
What property of an associative array does an object fail to
match?
</devil's advocate>
Until JavaScript/JScript engine producer will rectify this obvious bug,


It is not a bug. It is clearly defined behaviour.


Hear, hear.
I can't even see what the bug should be, except the failure to protect
the abstraction that is an array from its implementation.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #22

P: n/a
JRS: In article <ll**********@hotpop.com>, dated Sun, 19 Jun 2005
18:09:37, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :

You can do that, and most of the time it will work fine for
you. However, there will be the odd case where understanding how
arrays work, in particular that the length property only guarantees
to be at least one larger than the highest array index in use, is ^ integer ?necessary.

The prime point is the one I made before; that the length property does
not in the general case reflect the total number of elements, but is
associated with the number of non-negative-integer-index elements.

It is in fact associated with the way in which arrays work in Algol,
Pascal, and I presume C; and arrays in javascript are often used in that
manner, with integer indexing.

Once that is understood, it will sometimes be necessary to go into the
matter further.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #23

P: n/a
Lasse Reichstein Nielsen wrote:
<snip>
Safer languages protects their abstractions, Javascript
is not one :)
So let's not pretend it is safe, because it will turn and bite those who
assume it is.

<snip> <devil's advocate>
What property of an associative array does an object
fail to match?
</devil's advocate>

<snip>

The common expectation of an "associative array" seems to be that the
number of key/value pairs assigned will be reflected in a - length -
property. Hence the disappointment when javascript does no such thing.

Richard.
Jul 23 '05 #24

P: n/a
On 19/06/2005 22:18, Dr John Stockton wrote:
JRS: In article <ll**********@hotpop.com>, dated Sun, 19 Jun 2005
18:09:37, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
[...] the length property only guarantees to be at least one larger
than the highest array index in use [...]


^ integer ?


Array indicies are a subset of object property names, and are only
defined in terms of 32-bit unsigned integers, so it would seem redundant.

[snip]

Could I ask a small favour of you, John? Can you check if IE4 supports
String.prototype.charCodeAt? Microsoft's documentation says it doesn't,
but my copy does. Though it is running on XP, it has a separate
jscript.dll library and should be independent from the system libraries.
It is with regard to other methods like Array.prototype.push.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #25

P: n/a
On 19/06/2005 23:18, Lasse Reichstein Nielsen wrote:
Michael Winter <m.******@blueyonder.co.invalid> writes:
I disagree. The array:

[, 1]

has two elements, and a length of two.
[...] I would say that this array has one element and a length of two.


Whilst I still disagree, I do find it somewhat difficult to put into
words why. Perhaps it's my definition of what an array is, and why they
are normally used; a consequence of the notion of continuity, even if
the array is sparse.
It matters (to me) that the array doesn't have a property called "0".
Although I understand that the property '0' doesn't exist in that

[, 1].hasOwnProperty('0')

returns false (interestingly, Firefox returns true), it still does have
a 0th element. It is a zero-indexed array, sparse or otherwise, so it
must have all of the elements in the range [0, length).

[snip]
<devil's advocate>
What property of an associative array does an object fail to
match?
</devil's advocate>
rf answered this one a while ago. In most ways, native objects do
resemble associative arrays. They possess both put and get operations,
and indicies are not limited to just numbers. However, a native object
is never empty. This renders get operations vulnerable to cases where a
prototyped property is returned as an element, which could include
arbitrary properties introduced by user code.

Though this problem could be mitigated by user code, the associative
array is now a user object, and not a native object.

[Regarding non-array index properties not affecting length]
I can't even see what the bug should be [...]


I didn't mean for the summary about to answer the question, but that's
my understanding of it.

Mike
Does the subject of this thread need to be changed so that each post
isn't flagged as a potential FAQ entry?

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #26

P: n/a
Michael Winter <m.******@blueyonder.co.invalid> writes:
It is a zero-indexed array, sparse or otherwise, so it must have all
of the elements in the range [0, length).
So this is what it boils down to :)
Should a sparse datastructure be considered to have elements even
where they are not specified? I say no :)
However, a native object is never empty. This renders get operations
vulnerable to cases where a prototyped property is returned as an
element, which could include arbitrary properties introduced by user
code.


So the property it fails to have is the ability to be empty.
That's good enough for me :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #27

P: n/a
VK
> Does the subject of this thread need to be changed
so that each post isn't flagged as a potential FAQ entry?


Maybe, but how to call this new thread? Actually it's asking for
another
<FAQENTRY> title like "Does the world really exist or it's given to me
in my sensations and experience only?"

I don't really understant this attempt to alienate JavaScript
from any other language as it was written on Mars. It has the
most of the same entities as any other programming environment.

Any programming language is an abstraction. There is only two
real things: loaded/unloaded (1/0) memory cells and processor
flags after reading these cells. From this point of view there
is only one *real* language: ASSEMBLER (w/o mnemonics of course
as a disturbtion of the purity of the picture). Anything atope
of it as a *human abstraction* to desribe the movement and
allocation of these loads in the cells. There are not any objects,
arrays, hashes, variables etc. All from above is a kind of
"public agreement" in the meaning of Plato and Aristotle.
Nothing could us stop from deciding that say "array" would be
a data conglomerate where every second item starts with "A"
(or something even more bizzare).
On the OOP level any language consists of a set of objects,
where each object inherits/overloads/adds some method/properties
to the original Object (the Father of Gods). I don't see here
any major difference from any language. You can create a Data()
object in JavaScript and use it to play your media clips. You can
create a Array() object in JavaScript and use it to hold your
hash table. (Both by extending its properties or by changing
its prototype). Do you think that JavaScript is the most flexible
here? Some languages support operator's overload. So if you are
really bored at some sleepless night, you can make "+" sign to act
as "-" and vice versa. But do we need to state that Java
(that supports it) doesn't have a "+" sign but some "math object"
acting upon how do you use it?
If we stay at this point of view then there is no any fixed object,
and we're always acting with "something that can be anything" and the
only truth may come from our runtime experience. That puts us into
the most low level of the idealisme subjectif bordering with
a pure sensualisme.

IMHO You should respect profoundly the "public agreements"
about array and hash table (map, collection).
Otherwise you're the person who doesn't pay his bills on time
(because you're benefiting of something created 'cause of a public
agreement, but you don't want to follow that agreement right after).

In the particular, if you do var arrayObject = new Array();
you have to treat arrayObject as an array exclusively.
Otherwise why the hell did you create it?

Jul 23 '05 #28

P: n/a
In article <11**********************@z14g2000cwz.googlegroups .com>, VK
<sc**********@yahoo.com> writes

<snip>
In the particular, if you do var arrayObject = new Array();
you have to treat arrayObject as an array exclusively.
Otherwise why the hell did you create it?


Is that what you're trying to say : don't misuse Array objects; if you
do you'll get into trouble. I wish you'd learn to say it more clearly.

John
--
John Harris
Jul 23 '05 #29

P: n/a
In article <11**********************@z14g2000cwz.googlegroups .com>, VK
<sc**********@yahoo.com> writes

<snip>
On the OOP level any language consists of a set of objects,
where each object inherits/overloads/adds some method/properties
to the original Object (the Father of Gods).

<snip>

C++ doesn't have an 'original object' type, and is all the better for
it.

John
--
John Harris
Jul 23 '05 #30

P: n/a
JRS: In article <lN******************@text.news.blueyonder.co.uk >,
dated Sun, 19 Jun 2005 22:59:29, seen in news:comp.lang.javascript,
Michael Winter <m.******@blueyonder.co.invalid> posted :
On 19/06/2005 22:18, Dr John Stockton wrote:
JRS: In article <ll**********@hotpop.com>, dated Sun, 19 Jun 2005
18:09:37, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
[...] the length property only guarantees to be at least one larger
than the highest array index in use [...]
^ integer ?


Array indicies are a subset of object property names, and are only
defined in terms of 32-bit unsigned integers, so it would seem redundant.

Commonly, that which is used in conjunction with an array name to
indicate a specific element of an array will be considered, rightly or
wrongly, to be an array index; so ISTM useful to include an adjective as
a reminder even if it is in truth superfluous.

BTW, I should have included non-negative; good languages can allow
negative indexes.
Could I ask a small favour of you, John? Can you check if IE4 supports
String.prototype.charCodeAt? Microsoft's documentation says it doesn't,
but my copy does. Though it is running on XP, it has a separate
jscript.dll library and should be independent from the system libraries.
It is with regard to other methods like Array.prototype.push.


Not sure what you mean there.

"qwertyuiop".charCodeAt(5)

has the value 121, matching "y" and
"qwer\u0646yuiop".charCodeAt(5) -> 121
"qwer\u0646yuiop".charCodeAt(4) -> 1606 d wok / dt

Otherwise, if you send test code I'll try it.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #31

P: n/a
VK wrote:
<snip>
I don't really understant this attempt to alienate JavaScript
from any other language as it was written on Mars. It has the
most of the same entities as any other programming environment.

<snip>

There isn't an attempt to alienate javascript from other languages.
There is an attempt to understand what javascript is. It is very useful
to understand what javascript is if you are going to program it, and not
particularly helpful to know what VBScritp is.

There are certainly plenty of things that are very similar in any
programming language. A while loop is much the same everywhere, and
recognisable as a while loop even in assembly language. But the aspects
of any language that need most effort to appreciate are the aspects that
make it distinct from other languages. And in many respects javascript
is very distinct, and its closest relatives are not Java and C++,
regardless of syntactic similarities.

However, it is in the nature of javascript that if you can recognise a
concept in any other language you can implement it in javascript. So,
conceptually, you can have a class hierarchy, private object members,
multiple inheritance, and anything else you can think of from a class
based language. Not because these things are part of javascript but
because they can be created with javascript.

The problem being that while you can design and create javascript with
concepts borrowed from class-based languages you cannot do so without
understanding javascript, and you cannot understand javascript in terms
of the concepts from class-based languages (not even its OO aspects).

In the end the value of the approach you take towards understanding a
programming language can be judged by how effective it is. You have
spent the last couple of months posting absolute twaddle about event
handlers, and disregarding the various corrections and suggestions you
have been offered along the way. But when it came down to it Mike Winter
knew how to meet the challenge you set him with _one_line_of_code_. He
has known how to do that for some considerable time, and he attempted to
explain it to you in detail at lest twice.

Under the circumstances you have to wonder why you winged-on about
browser bugs and "this is that" for a couple of months while surrounded
by scores of individuals who self evidently were having no problems
employing event handlers. The obvious conclusion is that the conceptual
model that you use to understand javascript is fatally flawed. That it
is that that gets in the way of you understanding whet you are
attempting.

There is not much point in arguing that javascript may be understood in
the particular way that you are comfortable with when in your case that
style of conception is so evidently ineffective, and the people you are
arguing with are the ones that understand javascript (and don't spend
months going round in circles), and so have learnt how it can be best
understood.

Much better to take that advice you have been given and start to learn
the language you are using.

Richard.
Jul 23 '05 #32

P: n/a
On 20/06/2005 20:32, Dr John Stockton wrote:

[snip]
BTW, I should have included non-negative; good languages can allow
negative indexes.
To address memory locations prior to element 0? Languages that actually
implement arrays in the traditional sense could do that, or course, but
one could hardly expect ECMAScript to allow that.

[snip]
Not sure what you mean there.

"qwertyuiop".charCodeAt(5)

has the value 121, matching "y" [...]


That's what I meant, though I should have asked if you are running IE4
with its original JScript implementation, or have you upgraded that
separately?

As I said, Microsoft's documentation states that
String.prototype.charCodeAt is implemented as of JScript 5.5, but the
IE4 I'm running uses an earlier version and still implements the method.
I was wondering if that was somehow a product of running on XP (which I
doubt), or if the documentation is wrong.

Thank you,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #33

P: n/a
VK
To finalize (read <APPENDIX> at the bottom if more interested)

To stop this <FAQENTRY> from flaggering like a hell's gates counter,
I'm proposing a UN Counsil style text (no politics discussions, only
fully mutually acceptable points).

<FAQENTRY>
<QUE>
I'm doing:

var myObject = new Array();
var myObject["StringIdentifier"] = IdentifierValue;

But myObject.length doesn't change. What a hay? I event tried:

var myObject = new Object();
var myObject["StringIdentifier"] = IdentifierValue;

but it doesn't help!
</QUE>
<ANS>
The myObject.length property is set properly
only for an array which you have declared
by using var myObject = new Array() or by
var myObject = [item1, item2, item3]
and only if you're using positive integers for identifiers.
If some of your identifiers are strings, they will not be counted
to the myObject.length. In the particular, all form values come
to the function as strings. So even if your textField.value contains
a number, it will be treated as a string. So to ensure that
myObject.length
is set properly, you should do at the least:
var myObject[+Identifier] = IdentifierValue;
</FAQENTRY>

I think that now it's up to the group moderator to decide is this FAQ
is F (frequent) enough to include it into the list. (my opinion is
"YES", but it's only my IMHO). Upon his positive decision we could
bring it to a totally mutually acceptable form.

<APPENDIX>
So you think that var mapObject = {}; and var arrayObject = []; do the
same ?

You think that ability to link a proprietary amount of indexes (=>
dimentions) to a single value doesn't differ anyhow an array from a
hash table (where on has hard key/value links) ?

You think that the "random" order the key/value pairs are allocated in
memory baskets doesn't differ from the strict index based order of
array elements ?

Fine by me.

I'm going eazy with it now supported by two good proverbs:

(1) An old Persian one:
"Who can stop Hafiz from liken a ladybug to The Padishah?"
(means you can compare anything with anything as long as you see a
reason for it).

(2) The one came from modern China:
"It is no matter what color is the cat as long as it still hounts the
mice."
(means as long it works, it's fine)
</APPENDIX>

Jul 23 '05 #34

P: n/a
VK
Did you ever program using C++ or you're just sharing with the
community some terrible hightmares you had recently? Did you see a
deriving classe there or it was swalowed by a fire-breathing dragon?

Dr. VK

Jul 23 '05 #35

P: n/a
VK
> C++ doesn't have an 'original object' type,
and is all the better for it.


My previous reply on your post was on the level of a profanity.
I'm sorry in front of you, it's not my style really.
Yes, in C++ you're protected on the level of the language
promitives at least. (so array is always an array for you,
leaving the operators' overloading "leak" though). But
would you like to see a requirement to treat your class B
exactly as class A just because your class B was
derived from class A ??

Jul 23 '05 #36

P: n/a
"VK" <sc**********@yahoo.com> writes:

The myObject.length property is set properly
only for an array which you have declared
by using var myObject = new Array() or by
var myObject = [item1, item2, item3]
That is, for an array, no matter how it is instantiated (not
"declared").
and only if you're using positive integers for identifiers.
(within the range 0..2^32-2)
If some of your identifiers are strings, they will not be counted
to the myObject.length.
Incorrect. The parameter of the square bracket notation is always
converted to a string. If that string is a 32 bit integer in canonical
form (i.e., a valid array index), then assigning might change the
length property of the array. (Canonical form here means no initial
zeros, decimal point or exponential notation, so "1" is an array index
while "01", "1.0" and "1E+0" are not).
In the particular, all form values come
to the function as strings.
What function? The value property of form controls are strings.
So even if your textField.value contains
a number, it will be treated as a string. So to ensure that
myObject.length
is set properly, you should do at the least:
var myObject[+Identifier] = IdentifierValue;


Not necessary if the string is the canonical representation of an
appropriate integer.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #37

P: n/a
JRS: In article <11**********************@z14g2000cwz.googlegroups .com>
, dated Tue, 21 Jun 2005 10:36:48, seen in news:comp.lang.javascript, VK
<sc**********@yahoo.com> posted :
Did you ever program using C++ or you're just sharing with the
community some terrible hightmares you had recently? Did you see a
deriving classe there or it was swalowed by a fire-breathing dragon?

<FAQENTRY>
If you find that, when you start a News reply, Google does not provide
the previous article in quoted form, note what Keith Thompson wrote in
comp.lang.c, message ID <ln************@nuthaus.mib.org> :-
If you want to post a followup via groups.google.com, don't use
the "Reply" link at the bottom of the article. Click on "show
options" at the top of the article, then click on the "Reply" at
the bottom of the article headers.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME
Web <URL:http://www.uwasa.fi/~ts/http/tsfaq.html> -> Timo Salmi: Usenet Q&A.
Web <URL:http://www.merlyn.demon.co.uk/news-use.htm> : about usage of News.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Jul 23 '05 #38

P: n/a
JRS: In article <tn******************@text.news.blueyonder.co.uk >,
dated Tue, 21 Jun 2005 10:56:25, seen in news:comp.lang.javascript,
Michael Winter <m.******@blueyonder.co.invalid> posted :
On 20/06/2005 20:32, Dr John Stockton wrote:

[snip]
BTW, I should have included non-negative; good languages can allow
negative indexes.


To address memory locations prior to element 0? Languages that actually
implement arrays in the traditional sense could do that, or course, but
one could hardly expect ECMAScript to allow that.


I don't see why not, except on the basis of the language having been
written in a country that never developed its own natural language.
In Pascal/Delphi, array indexes are given upper and lower bounds, and
indexing can be by any ordinal type (i.e. boolean, enumerated, or any
variety of integer except comp and maybe Int64 (IIRC)).

"qwertyuiop".charCodeAt(5)

has the value 121, matching "y" [...]


That's what I meant, though I should have asked if you are running IE4
with its original JScript implementation, or have you upgraded that
separately?


Original; had I changed it, I'd probably have remembered to say.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #39

P: n/a
On 21/06/2005 20:54, Dr John Stockton wrote:

[JRS:]
[...] good languages can allow negative [array] indexes.

[MLW:] [...] one could hardly expect ECMAScript to allow that.
I don't see why not [...]


At face value, negative indices have value in languages that use pointer
arithmetic to address array elements. However, an ECMAScript
implementation is more likely to use a map to implement arrays.
In Pascal/Delphi, array indexes are given upper and lower bounds [...]


I'm unfamiliar with Pascal (though it's usually readable), so I can't
comment in any detail, but I would expect those arrays to be created
normally, but any index would be offset automatically to address the
array normally. A compiled language could optimise such operations to
the point of removing them altogether, but not a purely interpreted
language.

As this feature can be emulated trivially by a programmer, it doesn't
appear in many languages so there's no impetus to add it to ECMAScript,
either.

[snip]

In all, I don't particularly see the value.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #40

P: n/a
VK wrote:
Dear Richard,
This is a public newsgroup, not private e-mail.
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.
If so, you did that in a very poor way. Make it better next time.
Also pls do not look at this as an attack onto JavaScript.
I doubt it was. Sorry, but the reply simply showed in detail your ongoing
cluelessness on the group's main topic.
It was a BASIC of Internet,
Pardon? You want to read e.g. RFCs 1 to 100.
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.


First, JavaScript 1.0 is dated March 1996 as it was introduced with Netscape
Navigator 2.0 (JScript, and consequently ECMAScript emerged later); not
even 10 years have passed since then. Second, the features described do
NOT present limitations at all nor are they in any way simple (as already
shown). You really want to stop posting such FUD garbage here (unless you
are have now deliberately chosen to make a complete fool out of yourself).
Only because you are not able to handle it, it is by far not a Bad Thing,
especially when one takes the low level of expertise into account that you
presented here so far.
PointedEars
Jul 23 '05 #41

P: n/a
Lasse Reichstein Nielsen wrote:
While I think I understand your point, comparing Javascript
to a class based language is rarely productive.


While the statement applies only to JavaScript prior to v2.0,
JScript prior to v7.0/.NET and ECMAScript prior to ed. 4 ;-)
SCNR

PointedEars
Jul 23 '05 #42

P: n/a
Thomas 'PointedEars' Lahn <Po*********@web.de> writes:
While the statement applies only to JavaScript prior to v2.0,
JScript prior to v7.0/.NET and ECMAScript prior to ed. 4 ;-)


I have come to the point where I cannot tell whether I am deliberatly
ignoring this kludge on the side of Javascript or I have actually
managed to forget it. I guess it depends on what day it is :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #43

P: n/a
VK
Secently I noticed your pointed ears all around my postings. No to say
I was impressed too much by them (I mean postings). For example your
comments about <204 No Content> trick:
<http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/2cc6b164d27077eb/e3c81c8a05c002f4?q=204+No+Content&rnum=1#e3c81c8a0 5c002f4>
demonstrates that you must be never wrote a single line in Perl.

You want a shoot? I'll give you a shoot. This FAQENTRY material is
obsolete by now. Would you be intersted to discuss the new one:
<http://www.geocities.com/schools_ring/ArrayAndHash.html> (it has the
link on the related thread in this group).

Jul 23 '05 #44

P: n/a
VK wrote:
Secently I noticed your pointed ears all around my postings. No to say
I was impressed too much by them (I mean postings).
I am not surprised by that statement. You appear to be not impressed by
anything (not even a specification or reference written by the people who
created what you try to use) which is why you drop mostly gibberish
postings here.
For example your comments about <204 No Content> trick:
<http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/2cc6b164d27077eb/e3c81c8a05c002f4?q=204+No+Content&rnum=1#e3c81c8a0 5c002f4> demonstrates that you must be never wrote a single line in Perl.


I had not much practice in that language, but I had not none.
My suggestion works:

| $ perl -v
|
| This is perl, v5.8.7 built for i386-linux-thread-multi
| [...]
| $ perl
| print "HTTP/1.0 204 No content\r\nx";
| [^D]
| HTTP/1.0 204 No content
| x

It should also work in a CGI script. What is your point?
PointedEars
Jul 23 '05 #45

P: n/a
VK
> | $ perl -v
|
| This is perl, v5.8.7 built for i386-linux-thread-multi
| [...]
| $ perl
| print "HTTP/1.0 204 No content\r\nx";
| [^D]
| HTTP/1.0 204 No content
| x


#!/usr/bin/perl
# The above must be always the very first line
# otherwise 500 Internal Server Error

use strict;
# the -w flag (not -v : it stays from WarningsOn)
# is usable from command prompt only
# that is not a case for a CGI script
# use strict pragma does the same trick here

print "Status: 204 No content\n";

# Double new line indicates in HTTP the end
# of headers and start of document body (if any)
# So in this space I still can send *whatever I want*
# to the browser despites it stays on the current page
# if you bother to install Amaya, I'll show it to you.
# And you *never* use anything but new lines \n in Perl headers.
# It's not Windows or Mac, it's CGI transport
# over HTTP.

print "\n\n";
# end of transmission
exit(0);
# end of prog
It's not a Perl group, but just to make my point.
And yes, I like this group, because it has a lot of smart people in
here.
And no, I don't like W3 and ECMA too much and I don't believe that
every word they say is a truth in its last instance.

And actually W3 and ECMA *are not creators* of any kind of what we are
using. We are using stuff invented and developed by smart guys in
Switzerland and in the USA Netscape and Microsoft labs mainly and
mostly.

Jul 23 '05 #46

P: n/a
VK wrote:
| $ perl -v
|
| This is perl, v5.8.7 built for i386-linux-thread-multi
| [...]
| $ perl
| print "HTTP/1.0 204 No content\r\nx";
| [^D]
| HTTP/1.0 204 No content
| x


#!/usr/bin/perl
# The above must be always the very first line
# otherwise 500 Internal Server Error

use strict;
# the -w flag (not -v : it stays from WarningsOn)
# is usable from command prompt only
# that is not a case for a CGI script
# use strict pragma does the same trick here

print "Status: 204 No content\n";

# Double new line indicates in HTTP the end
# of headers and start of document body (if any)
# So in this space I still can send *whatever I want*
# to the browser despites it stays on the current page
# if you bother to install Amaya, I'll show it to you.
# And you *never* use anything but new lines \n in Perl headers.
# It's not Windows or Mac, it's CGI transport
# over HTTP.

print "\n\n";
# end of transmission
exit(0);
# end of prog
It's not a Perl group, but just to make my point.
And yes, I like this group, because it has a lot of smart people in
here.
And no, I don't like W3 and ECMA too much and I don't believe that
every word they say is a truth in its last instance.

And actually W3 and ECMA *are not creators* of any kind of what we are
using. We are using stuff invented and developed by smart guys in
Switzerland and in the USA Netscape and Microsoft labs mainly and
mostly.


With regard to HTTP, the specifications for the format of an HTTP
message are fairly universally implemented.

In the particular, the status line should be transmitted as:
HTTP/<major-version>.<minor-version><SP><status-code><SP><status-message><end-of-line>

Anything else is almost universally ineffectual, which is why it didn't
work for you. Doing Status: etc would have the effect of the server
providing its own status line and the client respecting it. The status
line provided by the server in this instance would almost certainly
have been
HTTP/1.<zero or one> 200 OK
Which would have defeated your attempt to send a 204 No Content.
Also:
<end-of-line> is CRLF, not LF, I'm pretty sure (please correct me if
I'm wrong).
As a PERL programmer, remember the oft-repeated addage: be strict in
what you provide; be tolerant in what you accept. Provide the CRLF
according to spec, but accept either \r, \n, or \r\n.

PERL-wise, use strict is not necessary in the script we're talking
about, but that's minor. Using it in this case results in unnecessary
overhead.

The shebang line (#!<path-to-perl-binary>) is not "always" necessary--
this is dependent upon the server config. For instance, in IIS (at
least up to 4.0), it is ineffectual. If your Apache is configured
accordingly, the shebang might also be ignored. To be sure, it's "best"
to include it for portability, but it is certainly not "always
necessary".

The script you've written above should have been written, simply:

#!/usr/bin/perl
print "HTTP/1.0 204 No content\r\n\r\n";

Effectually little different from that proposed by our pointed-eared
friend, except that the message header is terminated by <CRLF><CRLF>,
instead of just <CRLF>.

Jul 23 '05 #47

P: n/a
"Christopher J. Hahn" schrieb:
The script you've written above should have been written, simply:

#!/usr/bin/perl
print "HTTP/1.0 204 No content\r\n\r\n";

Effectually little different from that proposed by our pointed-eared
friend, ^^^^^^
That would go to far, really.
except that the message header is terminated by <CRLF><CRLF>,
instead of just <CRLF>.


That is why I wrote "should contain at least" but VK again did not care
to read.
Regards,

PointedEars
Jul 23 '05 #48

This discussion thread is closed

Replies have been disabled for this discussion.