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

Testing Whether A Key Exists In An Associative Array

P: n/a
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 perhaps it
would be better to try a perl-like solution, using an "associative
array" as I would use a hash in perl. In perl, I would do this by
simply checking whether a hash element is defined for a particular key.
This avoids checking each value in the array.

my %chked_cells;
my $this_cell;

if (! defined $chked_cells{$this_cell}){
$chked_cells{$this_cell} = 1;
}

In javascript, as far as I can tell, the corresponding code would look
something like this:

var chked_cells = new Array;
var this_cell;

if (!chked_cells[this_cell]){
chked_cells[this_cell] = true;
}

But, I think this doesn't work because there is no javascript equivalent
to the perl's "defined" function (and javascript handles undefined
variables differently, I think). In javascript, this snippet returns an
error saying that chked_cells doesn't have any properties. I cannot
figure out how to do the test in similar way, though I have seen testing
a variable to see whether it is undefined, I haven't been able to make
that work here (because the array is defined?).

Is there a way to use an associative array in this way? Is there a
better way?

Thanks very much.
Jul 23 '05 #1
Share this Question
Share on Google+
21 Replies


P: n/a
scandal <sc******@erkbfhk.com> writes:
In javascript, as far as I can tell, the corresponding code would look
something like this:

var chked_cells = new Array;
This is fine. I normally write
var chked_cells = new Array();
or just
var chked_cells = [];
but it should be equivalent. Since you are using integer indices,
an array might be more efficient than a plain object, but if
you don't use the "length" property, it should work the same, i.e,
you could also write:
var chked_cells = new Object();
var this_cell;
I assume it will be given an integer value before it is used:
if (!chked_cells[this_cell]){
chked_cells[this_cell] = true;
}

But, I think this doesn't work because there is no javascript
equivalent to the perl's "defined" function (and javascript handles
undefined variables differently, I think).
Reading undeclared variables gives an error. Reading undefined
properties of an object just gives the value "undefined". I don't
remember enough Perl to say how different that is :)
In javascript, this snippet returns an error saying that chked_cells
doesn't have any properties.
Then there is something wrong. In fact, just cutting and pasting the
five lines gives me no errors when running it, so this is not the
code that you are having problems with. Can you show us a small,
self-contained example that fails in this way?
I cannot figure out how to do the test in similar way,
though I have seen testing a variable to see whether it is undefined,
I haven't been able to make that work here (because the array is
defined?).
Testing for a property can be done in several ways. The simplest is
just:

if (object[propName]) { //.. defined and not falase

It fails if the values can be false. More precise would be:

if (object[propName] !== undefined) { // ... not undefined

Since you can assigne "undefined" as a value to a property, you
won't catch that this way. Even more precise is:

if (propName in object) { // object definitly has property propName

This also tests the prototype chain, so ("toString" in object) will
be always true, since Object.prototype.toString is in the prototype
chain. The most precise test is:

if (object.hasOwnProperty("propName")) { // ...

It only tests the properties assigned directly to this object.
Is there a way to use an associative array in this way?
Absolutely.
Is there a better way?


Yep. But until you tell us what way you do it, in details, we can't
tell you how to do it better :)

/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 #2

P: n/a
VK
> Is there a way to use an associative array in this way?

var hash = {'foo':'key1', 'bar':'key2'};

if (hash['foo']) {// gives you true
}

if (hash['qwerty']) {// gives you false
}

Three notes for a Perl-comer ;-)

1) Hash notation is currupted in JavaScript for legacy issues (to
accomodate code/traditions from the Netscape era).
So despite you do:
var hash = {'foo':'key1', 'bar':'key2'};
later you address the values like:
hash['key'] = value;
instead of proper hash{'key'} = value

2) "hash" is not a reserved word

3) Comparison is very simplified Thus both null and undefined equal
false in comparison operations.

Jul 23 '05 #3

P: n/a
"VK" <sc**********@yahoo.com> writes:
3) Comparison is very simplified Thus both null and undefined equal
false in comparison operations.


More precisely: In contexts where a boolean is needed (e.g., the
condition expression of an "if", "for" or "while" statement, or as
parameter to logival operators like "!" or "&&"), Javascript allows
any value, it's just converted to a boolean before testing.

The conversion to a boolean is the same as you get from calling the
"Boolean" function. Basically, all values are converted to true,
except: false, null, undefined, 0, NaN, and "" (the empty string).

All *objects* convert to true, even "new Boolean(false)" (surprise!).
Only basic types can convert to false, and they all have one value
that does (except numbers, which have two).

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

P: n/a
JRS: In article <4q**********@hotpop.com>, dated Wed, 6 Jul 2005
20:00:00, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :

All *objects* convert to true, even "new Boolean(false)" (surprise!).
Only basic types can convert to false, and they all have one value
that does (except numbers, which have two).


AIUI, those two are +0 and -0 and NaN .

Although +0 == -0 and +0 === -0 both give true in my system,
+0 and -0 are distinguishable values.

--
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 #5

P: n/a
Dr John Stockton <jr*@merlyn.demon.co.uk> writes:
AIUI, those two are +0 and -0 and NaN .
Ack. Indeed, Javascript inherits the existence of positive and
negative zero from IEEE 754. Why couldn't they just have collapsed
them into a single 0, just as they did for NaN.
Although +0 == -0 and +0 === -0 both give true in my system,
+0 and -0 are distinguishable values.


They are, at some level, but are they distinguishable form a
Javascript program's perspective? There us no method on
Number.prototype or on Math that distinguishes +0 and -0.

/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 #6

P: n/a
JRS: In article <ps**********@hotpop.com>, dated Thu, 7 Jul 2005
21:57:13, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
Dr John Stockton <jr*@merlyn.demon.co.uk> writes:
AIUI, those two are +0 and -0 and NaN .


Ack. Indeed, Javascript inherits the existence of positive and
negative zero from IEEE 754. Why couldn't they just have collapsed
them into a single 0, just as they did for NaN.
Although +0 == -0 and +0 === -0 both give true in my system,
+0 and -0 are distinguishable values.


They are, at some level, but are they distinguishable form a
Javascript program's perspective? There us no method on
Number.prototype or on Math that distinguishes +0 and -0.


But no method is needed. Just compare their reciprocals; two more
unequal numbers are hard to imagine. Or compare them with plus and
minus Infinity.

But, AFAIK, javascript does not support that form of maths in which
+Infinity and -Infinity are equivalent.

--
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 #7

P: n/a
VK
> But no method is needed. Just compare their reciprocals; two more
unequal numbers are hard to imagine. Or compare them with plus and
minus Infinity.


Bitwise operations show that in JavaScript -0 and 0 both kept as
positive 0:

alert(~(-0)); and alert(~(0)); both give you -1 (so minus bit is not
set in neither case).

So -0 is just a bogus in JavaScript, it doesn't have any internal
implementation.

Jul 23 '05 #8

P: n/a
In article <11**********************@o13g2000cwo.googlegroups .com>,
"VK" <sc**********@yahoo.com> wrote:
But no method is needed. Just compare their reciprocals; two more
unequal numbers are hard to imagine. Or compare them with plus and
minus Infinity.


Bitwise operations show that in JavaScript -0 and 0 both kept as
positive 0:

alert(~(-0)); and alert(~(0)); both give you -1 (so minus bit is not
set in neither case).

So -0 is just a bogus in JavaScript, it doesn't have any internal
implementation.

Did you actually try what was posted, i.e., 1/0 == 1/-0 ?

If that returned true, what browser?
Jul 23 '05 #9

P: n/a
JRS: In article <11**********************@o13g2000cwo.googlegroups .com>
, dated Mon, 11 Jul 2005 02:57:19, seen in news:comp.lang.javascript, VK
<sc**********@yahoo.com> posted :
But no method is needed. Just compare their reciprocals; two more
unequal numbers are hard to imagine. Or compare them with plus and
minus Infinity.


Bitwise operations show that in JavaScript -0 and 0 both kept as
positive 0:

alert(~(-0)); and alert(~(0)); both give you -1 (so minus bit is not
set in neither case).

So -0 is just a bogus in JavaScript, it doesn't have any internal
implementation.


You have not understood the paragraph of mine that you quote above.

Your tests are inadequate; they are no better than showing that all
numbers are equal by multiplying with 0 before comparing. Operators can
lose information; they can indicate, but cannot create, it.
In my system, after var P = 0, M = -P, x = [P == M, 1/P == 1/M] ,
x is [true, false] -- and x = [+0 == -0, 1/+0 == 1/-0, +1/+0 == -1/-0]
gives [true, false, true].
Type Number in javascript, which is what +0 & -0 are, is an IEEE Double,
with possible values including +0 -0 +Infinity -Infinity NaN and
ordinary values. But when a Number is used as an argument to a logical
operator, it is first converted to a 32-bit signed integer, with loss of
information including the sign of zero.
In javascript, +0 and -0 are different.

--
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 #10

P: n/a
VK
> But when a Number is used as an argument to a logical
operator, it is first converted to a 32-bit signed integer, with loss of
information including the sign of zero.


"sign of zero" - what math entity is that? I used to think of a "sign
of number" or "sign bit" (on low level).

Bitwize AND deals with bitset representation of a number. So *sign* bit
will be reversed as well:

alert(~(10)) // -11 - became negative
alert(~(-10)) // 9 - became positive

The fact that both alert(~(0)) and alert(~(-0)) gives you -1 shows that
the sign bit is not set in neither case. I guess in situations like
1/-0 JavaScript doesn't deal with -0 as a "special number". It takes it
as an expression "zero with unary negation operator in front of it".

Jul 23 '05 #11

P: n/a
Zif
VK wrote:
But when a Number is used as an argument to a logical
operator, it is first converted to a 32-bit signed integer, with loss of
information including the sign of zero.

"sign of zero" - what math entity is that? I used to think of a "sign
of number" or "sign bit" (on low level).

Bitwize AND deals with bitset representation of a number. So *sign* bit
will be reversed as well:

alert(~(10)) // -11 - became negative
alert(~(-10)) // 9 - became positive

The fact that both alert(~(0)) and alert(~(-0)) gives you -1 shows that
the sign bit is not set in neither case. I guess in situations like
1/-0 JavaScript doesn't deal with -0 as a "special number". It takes it
as an expression "zero with unary negation operator in front of it".


Did you look in the ECMA specification?

1/-0 is *defined* as being -infinity, no other logic need be applied
(see section 11.5.2).

No doubt real mathematicians are appalled - the result should be
'undefined', but I suppose that since undefined is used elsewhere for
other purposes using it here would be too confusing - the concept of -0
not withstanding.
--
Zif
Jul 23 '05 #12

P: n/a
On 12/07/2005 07:06, VK wrote:
But when a Number is used as an argument to a logical operator, it
is first converted to a 32-bit signed integer, with loss of
information including the sign of zero.
"sign of zero" - what math entity is that?


Zero has no sign; neither positive nor negative. However, IEEE doubles
can represent a variety of numbers, including two representations of zero.

[snip]
The fact that both alert(~(0)) and alert(~(-0)) gives you -1 shows that
the sign bit is not set in neither case.
John already explained why, but perhaps you'll read it this time.

When bitwise NOT is applied to a UnaryExpression, that operand is first
converted using the internal ToInt32 operator. This forces all of
+Infinity, -Infinity, NaN, +0, and -0 to +0. The result is bound to be
either a positive or negative integer, or +0. Your test case shows nothing.
I guess in situations like 1/-0 JavaScript doesn't deal with -0 as a
"special number".


Of course it does, otherwise John's tests would have shown that 1/+0
equals 1/-0, but it doesn't: the results are +Infinity and -Infinity,
respectively.

Creating -0 seems less easy as none of my browsers seem to respect the
specification by creating -0 when the result of a multiplicative
operation (11.5) should be zero and one of the arguments is negative.

Perhaps something in IEEE 754 causes them to act differently? I'm not
familiar with it.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #13

P: n/a
Michael Winter <m.******@blueyonder.co.uk> writes:
Creating -0 seems less easy as none of my browsers seem to respect the
specification by creating -0 when the result of a multiplicative
operation (11.5) should be zero and one of the arguments is negative.


Which browsers are that? You are using Windows (according to your
User-Agent header), so you probably can test with IE. In my IE 6,
alert(1/(-1*0)) alerts -Infinity, i.e., (-1*0) is -0.

/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 #14

P: n/a
On 12/07/2005 12:37, Lasse Reichstein Nielsen wrote:
Michael Winter <m.******@blueyonder.co.uk> writes:
Creating -0 seems less easy [...]

Seems that 'all' was a little strong, but certainly all recent versions.
Which browsers are that?
Opera 8, IE4+, Mozilla 1.3->1.7, Firefox 1.0.4, and NN4.77. The only
browsers I have in Windows that behave correctly are Opera 6.06->7.54. I
haven't checked in Linux because, quite frankly, I can't be arsed. :D
You are using Windows [...]
I am.
In my IE 6, alert(1/(-1*0)) alerts -Infinity


** Plays in browsers **

Hmmm... That's odd.
** Looks at spec. **

Damn it!

I was expecting the sign to appear.
Errm, thanks Lasse. :)

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #15

P: n/a
VK
> Infinity and -0

Overall it was damn stupid to pull theoretical math staff into
computer, specially into ECMAScript (that doesn't have any precise-math
extention libraries).

alert(1.79E+308); // 1.79E+308
alert(1.79E+309); // Infinity

I'm a God-like how I guess: I'm the first human who mesured the exact
limits of the infinity. It starts right from 1.79E+309 :-)

There were two such nice errors: "Number too big" and "Division on
zero". And look what egg-heads did with it!

Jul 23 '05 #16

P: n/a
VK wrote:
Is there a way to use an associative array in this way?
var hash = {'foo':'key1', 'bar':'key2'};

if (hash['foo']) {// gives you true
}

if (hash['qwerty']) {// gives you false
}


And

var hash = {'foo': '', 'bar':'key2'};

if (hash['foo']) {// gives you false
}

Furthermore, property names in an object literal only have
to be within an object literal if they are not identifiers
and not numbers:

var hash = {foo: '', bar: 'key2'};
var hash = {2: '', 'bar': 'key2'};

and

var hash = {'foo': '', 'bar': 'key2'};
var hash = {'2': '', 'bar': 'key2'};

are valid and equivalent, while

var hash = {2n: '', 'bar': 'key2'};

gives a syntax error and

var hash = {'2n': '', 'bar': 'key2'};

does not.
Three notes for a Perl-comer ;-)

1) Hash notation is currupted in JavaScript for legacy issues (to
accomodate code/traditions from the Netscape era).
Rubbish. Objects have been since JavaScript 1.0!
So despite you do:
var hash = {'foo':'key1', 'bar':'key2'};
later you address the values like:
hash['key'] = value;
instead of proper hash{'key'} = value
Learn to understand that different languages use different syntaxes.
There is nothing generally "proper" in hash{'key'}.
2) "hash" is not a reserved word
`hash' is not a reserved word in Perl either. From perlintro(1):

my $variables = {
scalar => {
description => "single item",
sigil => '$',
},
array => {
description => "ordered list of items",
sigil => '@',
},
hash => {
description => "key/value pairs",
sigil => '%',
},
};

The above is perfectly valid Perl code. It would not if `hash' would
be a reserved word because then if must not be used as identifier.
Obviously you don't know what the term `reserved word' means.
3) Comparison is very simplified Thus both null and undefined equal
false in comparison operations.


That is not entirely true. First, there are more values that evaluate
to false in a boolean expression (of which comparison operations are
only one example), see above. Second, from JavaScript 1.3, JScript 1.0
and ECMAScript 3 on there are strict comparison operators supported
where no type conversion is performed, namely `!==' and `==='.
PointedEars
Jul 23 '05 #17

P: n/a
Thomas 'PointedEars' Lahn wrote:
Furthermore, property names in an object literal only have
to be within an object literal if they are not identifiers
and not numbers:


This should read:

Furthermore, property names in an object literal only have
to be within a _string_ literal if they are not identifiers
and not numbers:
PointedEars
Jul 23 '05 #18

P: n/a
VK wrote:
Is there a way to use an associative array in this way?
var hash = {'foo':'key1', 'bar':'key2'};

if (hash['foo']) {// gives you true
}

if (hash['qwerty']) {// gives you false
}


And

var hash = {'foo': '', 'bar':'key2'};

if (hash['foo']) {// gives you false
}

Furthermore, property names in an object literal only have
to be within a string literal if they are not identifiers
and not numbers:

var hash = {foo: '', bar: 'key2'};
var hash = {2: '', 'bar': 'key2'};

and

var hash = {'foo': '', 'bar': 'key2'};
var hash = {'2': '', 'bar': 'key2'};

are valid and equivalent, while

var hash = {2n: '', 'bar': 'key2'};

gives a syntax error and

var hash = {'2n': '', 'bar': 'key2'};

does not.
Three notes for a Perl-comer ;-)

1) Hash notation is currupted in JavaScript for legacy issues (to
accomodate code/traditions from the Netscape era).
Rubbish. Objects have been since JavaScript 1.0!
So despite you do:
var hash = {'foo':'key1', 'bar':'key2'};
later you address the values like:
hash['key'] = value;
instead of proper hash{'key'} = value
Learn to understand that different languages use different syntaxes.
There is nothing generally "proper" in hash{'key'}.
2) "hash" is not a reserved word
`hash' is not a reserved word in Perl either. From perlintro(1):

my $variables = {
scalar => {
description => "single item",
sigil => '$',
},
array => {
description => "ordered list of items",
sigil => '@',
},
hash => {
description => "key/value pairs",
sigil => '%',
},
};

The above is perfectly valid Perl code. It would not if `hash' would
be a reserved word because then if must not be used as identifier.
Obviously you don't know what the term `reserved word' means.
3) Comparison is very simplified Thus both null and undefined equal
false in comparison operations.


That is not entirely true. First, there are more values that evaluate
to false in a boolean expression (of which comparison operations are
only one example), see above. Second, from JavaScript 1.3, JScript 1.0
and ECMAScript 3 on there are strict comparison operators supported
where no type conversion is performed, namely `!==' and `==='.
PointedEars
Jul 23 '05 #19

P: n/a
VK
Finally some productive feedback from you! Need to further update my
text.
var hash = {'foo':'key1', 'bar':'key2'};

if (hash['foo']) {// gives you true
}

if (hash['qwerty']) {// gives you false
}
And

var hash = {'foo': '', 'bar':'key2'};

if (hash['foo']) {// gives you false
}


Yep. I over-simplified the property check.

More secure:

if (hashObject['foo'] == undefined) {...}

Super secure:

if ((!hashObject.prototype.hasOwnProperty('foo') ||
(hashObject.hasOwnProperty('foo')) {...}

Whis way you ensure that the object has this property and that this is
*your* property, not a stuff from the prototype.

Furthermore, property names in an object literal only have
to be within an object literal if they are not identifiers
and not numbers:

var hash = {foo: '', bar: 'key2'};
var hash = {2: '', 'bar': 'key2'};

and

var hash = {'foo': '', 'bar': 'key2'};
var hash = {'2': '', 'bar': 'key2'};

are valid and equivalent, while

var hash = {2n: '', 'bar': 'key2'};

gives a syntax error and

var hash = {'2n': '', 'bar': 'key2'};

does not.


That's very interesting! Did not understand your explanation though.
2 will be converted to "2"
foo to "foo"
even such key as $__$ can be provided w/o quotes
But something like {2n:'foo'} - not. It needs manual quoting. Why?

Jul 23 '05 #20

P: n/a
On 19/07/2005 15:50, VK wrote:

[snip]
More secure:

if (hashObject['foo'] == undefined) {...}
That will evaluate to true if the property is either null or undefined,
exactly as would happen if you wrote:

if (hashObject['foo'] == null) {...}

You could perform a strict comparison to eliminate the type conversion,
but it may be necessary to avoid problems where undefined isn't defined,
such as IE5 and earlier:

if('undefined' == typeof hashObject.foo) {...}
Super secure:

if ((!hashObject.prototype.hasOwnProperty('foo') ||
(hashObject.hasOwnProperty('foo')) {...}
The Object.prototype.hasOwnProperty method already ensures that the
prototype chain isn't considered. Moreover, that expression fails when
the object doesn't have a 'foo' property at all, inherited or otherwise.
Finally, the prototype property isn't used when finding property names;
the internal [[Prototype]] property is, and they don't need to match.

[Property names in object literals]
2 will be converted to "2"
foo to "foo"
even such key as $__$ can be provided w/o quotes
It's not a sodding key! It's a property name.
But something like {2n:'foo'} - not. It needs manual quoting. Why?


Well, to state the obvious: 2n doesn't match the PropertyName
production. That's the only explanation needed really, but to elaborate,
property names in object literals are either Identifier, StringLiteral,
or NumericLiteral tokens. The digit, 2, is a numeric literal, and the
sequences, foo and $__$, are identifiers. However, 2n is none of these
things, so it must be represented by a string literal.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #21

P: n/a
VK
> > Super secure:

if ((!hashObject.prototype.hasOwnProperty('foo') ||
(hashObject.hasOwnProperty('foo')) {...}


The Object.prototype.hasOwnProperty method already ensures that the
prototype chain isn't considered. Moreover, that expression fails when
the object doesn't have a 'foo' property at all, inherited or otherwise.
Finally, the prototype property isn't used when finding property names;
the internal [[Prototype]] property is, and they don't need to match.


Sorry, two typos (back-pay for a rush): of course AND (&&), not OR
(||); and reference to the class constructor... the constructor
function... is missing. Now you can play with prop:

function propertyCheck() {
var arrayObject = [];
arrayObject['foo'] = 'bar';
//var prop = "splice";
//var prop = "foo";
//var prop = "eggog";
if (arrayObject.constructor.prototype.hasOwnProperty( prop)) {
alert("["+prop+"]"+" is generic property for this object.");
}
else if (arrayObject.hasOwnProperty(prop)) {
alert("["+prop+"]"+" property added programmatically.");
}
else {
alert("["+prop+"]"+" property doesn't exists in this object.");
}
}
But something like {2n:'foo'} - not. It needs manual quoting. Why?


Well, to state the obvious: 2n doesn't match the PropertyName
production. That's the only explanation needed really, but to elaborate,
property names in object literals are either Identifier, StringLiteral,
or NumericLiteral tokens. The digit, 2, is a numeric literal, and the
sequences, foo and $__$, are identifiers. However, 2n is none of these
things, so it must be represented by a string literal.


That would be a great answer if you were my prof and decided to prompt
me a bit to pull my sorry D at least to C. It has no help otherwise to
the regular mortal people.
They do unquoted $__$, 1, qdjdj1234 etc.
And oops: unquoted 2n gives them an error.

They go to comp.language.javascript and see this encouraging info. They
google and found something like
<http://www.quirksmode.org/bugreports/archives/2005/06/Using_numbers_as_property_names_causes_syntax_erro .html>

(Yes, surprise, surprise: you "well defined behavior" is sliding to the
category of bugs, because no one publicly explained it yet.)
So what the hey: what does make 2n neither Identifier, StringLiteral,
or NumericLiteral tokens? 2 in front? number in front? n after 2? what
would be the universal pattern to sort it out?

Jul 23 '05 #22

This discussion thread is closed

Replies have been disabled for this discussion.