Get value of named object

S

Swifty

If I have the name of an object in a variable, how would I go about
getting the value of that object?

Example:
varname = 'navigator.appName';

How would I get the value of navigator.appName ?

See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.

The idea is to replace the multiple "document.write" lines with the
simpler "show()" calls.
 
E

Evertjan.

Swifty wrote on 22 okt 2011 in comp.lang.javascript:
If I have the name of an object in a variable, how would I go about
getting the value of that object?

myObject.name perhaps would return the name of an object.
Example:
varname = 'navigator.appName';

How would I get the value of navigator.appName ?

See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.

The idea is to replace the multiple "document.write" lines with the
simpler "show()" calls.

document.write( "<TR><TH>" + varname + "<TD>" + eval(varname) );

=================

Using eval() indeed is a variable blessing:

<H1>JavaScript Varibles</H1>
 
T

Thomas 'PointedEars' Lahn

Swifty said:
If I have the name of an object in a variable,

That is _not_ the name of an object (objects have _identity_, not name). It
is a possible reference path of a property (a property accessor) which value
refers to that object.
how would I go about getting the value of that object?

Example:
varname = 'navigator.appName';

How would I get the value of navigator.appName ?

eval(varname). But you really don't want to do that.
See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.

The idea is to replace the multiple "document.write" lines with the
simpler "show()" calls.

(Your current show() would still cause document.write() to be called
consecutively, which is a bad idea.)

Consider this:

var properties = [
["navigator", "appCodeName"],
["screen", "availHeight", "availWidth"],
["window", "closed", "history", "innerHeight", "innerWidth",
["location", "hostname", "pathname"], "outerHeight", "outerWidth"]
];

Then iterate recursively over this data structure, starting with

_global[properties[0]]

where `_global' is a reference to the ECMAScript global object (`this' in
the global execution context) and `i' is the iterator variable. Complete
and improve this:

var out = [];

for (var i = 0, len = properties.length; i < len; ++i)
{
var base = properties[0];
for (var properties2 = properties, len2 = properties2.length, j = 1;
j < len2; ++j)
{
var property = base[j];
out.push(
"…" + base + "." + property + "…" + _global[base][property] + "…");
}
}

document.write("…" + out.join("…") + "…");

You may use Object instances as well if you do not care about order or
iterate over property values in an order that you define. In any case,
you have to take care of inherited and special properties, then.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Swifty said:
If I have the name of an object in a variable,

That is _not_ the name of an object (objects have _identity_, not name). It
is a possible reference path of a property (a property accessor) which value
refers to that object.
how would I go about getting the value of that object?

Example:
varname = 'navigator.appName';

How would I get the value of navigator.appName ?

eval(varname). But you really don't want to do that.
See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.

The idea is to replace the multiple "document.write" lines with the
simpler "show()" calls.

(Your current show() would still cause document.write() to be called
consecutively, which is a bad idea.)

Consider this:

var properties = [
["navigator", "appCodeName"],
["screen", "availHeight", "availWidth"],
["window", "closed", "history", "innerHeight", "innerWidth",
["location", "hostname", "pathname"], "outerHeight", "outerWidth"]
];

Then iterate recursively over this data structure, starting with

_global[properties[0]]

where `_global' is a reference to the ECMAScript global object (`this' in
the global execution context) and `i' is the iterator variable. Complete
and improve this:

var out = [];

for (var i = 0, len = properties.length; i < len; ++i)
{
var properties2 = properties;
var base = properties2[0];
for (var j = 1, len2 = properties2.length; j < len2; ++j)
{
var property = base[j];
out.push(
"…" + base + "." + property + "…" + _global[base][property] + "…");
}
}

document.write("…" + out.join("…") + "…");

You may use Object instances as well if you do not care about order or
if you iterate over property values in an order that you define. In any
case, you have to take care of inherited and special properties, then.

Since you are dealing with host objects here, you have to be extra careful
with "unknown"-type properties and to catch any exceptions a property access
can throw.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Swifty said:
If I have the name of an object in a variable,

That is _not_ the name of an object (objects have _identity_, not name). It
is a possible reference path of a property (a property accessor) which value
refers to that object.
how would I go about getting the value of that object?

Example:
varname = 'navigator.appName';

How would I get the value of navigator.appName ?

eval(varname). But you really don't want to do that.
See http://swiftys.org.uk/jsvars.html for my first, faltering attempt.

The idea is to replace the multiple "document.write" lines with the
simpler "show()" calls.

(Your current show() would still cause document.write() to be called
consecutively, which is a bad idea.)

Consider this:

var properties = [
["navigator", "appCodeName"],
["screen", "availHeight", "availWidth"],
["window", "closed", "history", "innerHeight", "innerWidth",
["location", "hostname", "pathname"], "outerHeight", "outerWidth"]
];

Then iterate recursively over this data structure, starting with

_global[properties[0]]

where `_global' is a reference to the ECMAScript global object (`this' in
the global execution context) and `i' is the iterator variable. Complete
and improve this:

var out = [];

for (var i = 0, len = properties.length; i < len; ++i)
{
var properties2 = properties;
var base = properties2[0];
for (var j = 1, len2 = properties2.length; j < len2; ++j)
{
var property = properties2[j];
out.push(
"…" + base + "." + property + "…" + _global[base][property] + "…");
}
}

document.write("…" + out.join("…") + "…");

You may use Object instances as well if you do not care about order or
if you iterate over property values in an order that you define. In any
case, you have to take care of inherited and special properties, then.

Since you are dealing with host objects here, you have to be extra careful
with "unknown"-type properties and to catch any exceptions a property access
can throw.


PointedEars
 
S

Swifty

Using eval() indeed is a variable blessing:

<H1>JavaScript Varibles</H1>

Thanks for that, and eval()

I realise that eval() is disliked, as is the "Interpret" instruction
which does something similar in my usual language.
 
S

Swifty

(Your current show() would still cause document.write() to be called
consecutively, which is a bad idea.)

And there I was, congratulating myself on having very nearly written
an entire page in JavaScript. One step at a time.

The page is half learning exercise, half reference for properties that
interest me, and which I may eventually use somewhere.
 
T

Thomas 'PointedEars' Lahn

Swifty said:
[…] "Evertjan. said:
Using eval() indeed is a variable blessing:

<H1>JavaScript Varibles</H1>

Thanks for that, and eval()

I realise that eval() is disliked, as is the "Interpret" instruction
which does something similar in my usual language.

"Disliked" does not quite describe it.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Swifty said:
And there I was, congratulating myself on having very nearly written
an entire page in JavaScript. One step at a time.

The page is half learning exercise, half reference for properties that
interest me, and which I may eventually use somewhere.

If it is supposed to be a learning exercise, then you have slept right
through it. In essence:

1. Avoid using eval(). Use property access syntax instead.

2. Do not call document.write() consecutively. Pass it a string value
(or a value convertible to a string) that you build before.


PointedEars
 
S

Scott Sauyet

Swifty said:
If I have the name of an object in a variable, how would I go about
getting the value of that object?

Example:
varname = 'navigator.appName';

How would I get the value of navigator.appName ?

Seehttp://swiftys.org.uk/jsvars.htmlfor my first, faltering attempt.

An approach somewhat different from Thomas', and perhaps not as safe,
is the following:

var interpret = (function() {
var global = this;
return function(str) {
var idx, obj, context = arguments[1] || global;
if (!str || typeof str != "string") return null;
idx = str.indexOf(".");
if (idx > -1) {
obj = context[str.substring(0, idx)];
return interpret(str.substring(idx + 1), obj);
} else {
return context[str];
}
}
}());

console.log(interpret("navigator.appName"));
// Or document.write, or alert, or DOM manipulation

This will not work if you have a property name that includes a ".",
and it might have problems Thomas suggested with Host objects, but for
many use cases it will work fine.

-- Scott
 
L

Lasse Reichstein Nielsen

Swifty said:
If I have the name of an object in a variable, how would I go about
getting the value of that object?

Example:
varname = 'navigator.appName';

So this is the reference:
globalObject["navigator"]["appName"]

So:
<script>
var global = this;
function EvalReference(name) {
var parts = name.split(/\./g);
var current = global;
for (var i = 0; i < parts.length; i++) {
current = current[parts];
}
return current;
}
</script>

Then you can do:
EvalReference("navigator.appName"]
and get the expected result.

Yes, you can use eval instead. You must be certain to use global eval,
by calling it as an indirect call (not called "eval"). E.g.,
var indirectEval = eval;
var value = indirectEval("navigator.appName");
I still think it's a bad idea.

/L
 
D

Dr J R Stockton

In comp.lang.javascript message <a185a7pdddj3ui58j7a8rrtuivpe4gu92l@4ax.
If I have the name of an object in a variable, how would I go about
getting the value of that object?

Example:
varname = 'navigator.appName';

How would I get the value of navigator.appName ?


var Arr = varname.split(".") // gives ["navigator","appName"]

IIRC, there are only a few possibilities for Arr[0], so
var Obj = {"navigator": navigator; "document": document /*, ,,, */}
is feasible.

var Obj = {"navigator": navigator, "document": document,
"Math": Math /*, ,,, */}

var varname = 'navigator.appName';
var Arr = varname.split(".")
Result = Obj[Arr[0]][Arr[1]]

gives "Netscape", and for "Math.PI" gives about 22/7, and for
"document.writeln" gives "function writeln() { [native code]}".
Now make that a function.

To allow for inputs with other than one dot, start with Result=Obj, then
iterate through Arr (in the right direction) doing each index in turn.
Untested, therefore code not written here.

You might like said:
The idea is to replace the multiple "document.write" lines with the
simpler "show()" calls.

Consider
var Arr = []
Arr.push("6")
Arr.push(" fred")
document.write(A,join(""))
which is less typing per line of code.
 

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,057
Latest member
KetoBeezACVGummies

Latest Threads

Top