PDA

View Full Version : Renaming a variable


junkmail
05-06-2003, 09:16 PM
Hey,

Can anyone please tell me that if there is a way to rename a variable? for example

function DisplayMsg(message)
{
var message1 = "Hello";
var message2 = "World";
// Is there a way that computer will display message 1 by changing the variable name message to message+'the number'
alert(message)
// I know I can use if else or switch statements but I do not want to use that... is there another way?
}

<a href="#" onclick="DisplayMsg('1')">Go</a>

I would appretiate any help....
Thanks....:rolleyes:

arnyinc
05-06-2003, 09:43 PM
<html>
<head>
<script language="javascript">
function DisplayMsg(msgnum){
var message1 = "Hello";
var message2 = "World";
alert(eval('message'+msgnum))
}
</script>
</head>
<body>

<a href="#" onclick="DisplayMsg('1')">Go</a>

</body>

</html>

requestcode
05-06-2003, 11:39 PM
*** nevermind I should have read the previous post more closely.

You could also try this:
alert(eval("message"+msgnum))

junkmail
05-07-2003, 01:29 AM
Thanks alot for your help... I really appretiated

Graeme Hackston
05-07-2003, 03:36 AM
Here's another way that makes the variables available to the rest of the page.

<html>
<head>
<script type="text/javascript">
msgs = new Array("Hello","World")
msgs_length = msgs.length

for (var i=0; i<msgs_length; i++) {
window['message'+ i] = msgs[i]
}

function DisplayMsg(msgnum){
alert(window['message'+msgnum])
}
</script>
</head>
<body>

<a href="#" onclick="DisplayMsg('0'); alert(window['message' + '1'])">Go</a>

</body>

</html>

Graeme Hackston
05-07-2003, 03:46 AM
Other than being an example of window[] that's kinda silly. You can just do this with an array.

<html>
<head>
<script type="text/javascript">
msgs = new Array("Hello","World")
</script>
</head>
<body>

<a href="#" onclick="alert(msgs[0]); alert(msgs[1])">Go</a>

</body>

</html>