Select 1 value from multiple...

N

Noozer

I want to return one of several values, based on the value of a variable.

Is there a compact way to write this? Something like:

var J=5;
var K= {"One","Two","Three","Four","Five","Six"} [J] ;


.... so K would hold "Five" in this case.

Thx
 
D

Darren

Noozer said:
I want to return one of several values, based on the value of a variable.

Is there a compact way to write this? Something like:

var J=5;
var K= {"One","Two","Three","Four","Five","Six"} [J] ;


... so K would hold "Five" in this case.

Thx

Use an array.
var K=new Array("One","Two","Three","Four","Five","Six");
var J=4;
document.write(K[J]);
would produce 'five' remember that arrays start with a zero offset

Best wishes

Darren
 
N

Noozer

Klaus Johannes Rusch said:
Noozer said:
I want to return one of several values, based on the value of a variable.

Is there a compact way to write this? Something like:

var J=5;
var K= {"One","Two","Three","Four","Five","Six"} [J] ;


... so K would hold "Five" in this case.

var J=5;
var K= (new Array("One","Two","Three","Four","Five","Six"))[J-1];

Just wondering if there was a way to combine it on one line... No problem.
This works.
 
D

Dr John Stockton

JRS: In article <zcjKe.172865$s54.111428@pd7tw2no>, dated Wed, 10 Aug
2005 08:49:35, seen in Noozer
I want to return one of several values, based on the value of a variable.

Is there a compact way to write this? Something like:

var J=5;
var K= {"One","Two","Three","Four","Five","Six"} [J] ;


... so K would hold "Five" in this case.

var J=5;
var K= [,"One","Two","Three","Four","Five","Six"][J] ;

Changed {} to [] and insert comma.

Actually, K holds a reference to "Five"; in this case, that does not
matter, but in others it might.

Note that (AIUI) the array should be created whenever used; the
following would be more efficient in that case.

var Numbers = [,"One","Two","Three","Four","Five","Six"] ; // Global
....
var J = 5 ;
var K = Numbers[J] ;
 

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

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,117
Latest member
Matilda564
Top