eliminating eval

C

cp

If I have the following functions, is there a way to alter showData()
to get at the value of the array without resorting to an eval?


<html>
<head>
<title>Test</title>
<script type="text/javascript" language="javascript">
// <![CDATA[
var gRaces = new Array();
gRaces[ "elf" ]= { str:8, dex:10, con:6, 'int':8, wis:8,
cha:8 };
gRaces[ "half-elf" ]= { str:8, dex:10, con:8, 'int':8, wis:8,
cha:8 };
gRaces[ "half-orc" ]= { str:10, dex:8, con:8, 'int':6, wis:8,
cha:6 };

function showData(race, ab) {
alert( eval( 'gRaces[race].' + ab ) );
}
// ]]>
</script>
</head>
<body onload="showData('half-orc', 'int')">
&nbsp;
</body>
</html>
 
L

Lasse Reichstein Nielsen

cp said:
If I have the following functions, is there a way to alter showData()
to get at the value of the array without resorting to an eval?

Yes. (I say that before looking at the code, because I am a firm believer
in the abolishment of unneeded evals)


If you use XHTML, you should declare it somewhere. Otherwise,
CDATA-sections probably makes no difference
var gRaces = new Array(); ....
gRaces[ "half-elf" ]= { str:8, dex:10, con:8, 'int':8, wis:8,
cha:8 };

Half-elves don't have a racial bonus to dex. :p
function showData(race, ab) {
alert( eval( 'gRaces[race].' + ab ) );

Just as you write gRaces[race] instead of "gRaces."+race, you can use
square-bracket notation for ab:

alert(gRaces[race][ab])

See
<URL:http://jibbering.com/faq/#FAQ4_39>
and
<URL:http://jibbering.com/faq/#FAQ4_40>

/L
 
C

cp

Lasse Reichstein Nielsen said:
If you use XHTML, you should declare it somewhere. Otherwise,
CDATA-sections probably makes no difference

Thanks, I did (and do). I omitted the declaration for brevity.
var gRaces = new Array(); ...
gRaces[ "half-elf" ]= { str:8, dex:10, con:8, 'int':8, wis:8,
cha:8 };

Half-elves don't have a racial bonus to dex. :p

House rules? Kidding. Cut & Paste mistake
function showData(race, ab) {
alert( eval( 'gRaces[race].' + ab ) );

Just as you write gRaces[race] instead of "gRaces."+race, you can use
square-bracket notation for ab:

alert(gRaces[race][ab])

Thanks for that.
 
J

Jim Ley

Thanks, I did (and do). I omitted the declaration for brevity.

There are certainly no XHTML user agents that want the language
attribute on the script element.

There's also precious few XHTML user agents at all, probably best not
to use it.

Jim.
 

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
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top