Object properties

T

Tim Streater

I'm using an object as an associative array. It always has the property
"main", and may have others. So, when I create it I might do this:

var myobject = new Object ();
myobject["main"] = somevalue;

Other properties may be added later. Now, at some moment I need to know
whether myobject has just the one property, or several, and take
different actions depending.

So far all I've found to do something like:

flag = false;

for (i in myobject)
{
if (i=="main") continue;
flag = true;
break;
}

and then branch on flag. Or:

for (i in myobject)
{
if (i=="main") continue;
do_some_actions ();
break;
}


These approaches work but feel to me like I've overlooked something. Is
there a better approach?

TIA,
 
T

Thomas 'PointedEars' Lahn

Tim said:
I'm using an object as an associative array.

You should not do it like that.
It always has the property "main", and may have others.

It has or inherits other properties which are built-in. You should/must not
overwrite or shadow them. See also said:
So, when I create it I might do this:

var myobject = new Object ();

There should not be a space before the arguments list. Leave that style to
parenthesised operands instead.
myobject["main"] = somevalue;

var myobject = {
main: somevalue
};

is equivalent, and safe nowadays.¹
Other properties may be added later. Now, at some moment I need to know
whether myobject has just the one property, or several, and take
different actions depending.

Why would you need to know this?
So far all I've found to do something like:

flag = false;

Have you declared `flag' a variable?
for (i in myobject)

Have you declared `i' a variable?
{
if (i=="main") continue;
flag = true;
break;
}

and then branch on flag. Or:

for (i in myobject)
{
if (i=="main") continue;
do_some_actions ();
break;
}

These approaches work but feel to me like I've overlooked something.

See previous discussions about the caveats of for-in iteration.
Is there a better approach?

Apparently you are looking for a problem to your solution.


PointedEars
___________
¹ <http://PointedEars.de/es-matrix>,
but note that features may be marked as safe for which insufficient
information is available (fixed in the next revision)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top